2024/9/29 多维dp 1143. 最长公共子序列 dp解法
This commit is contained in:
parent
e7fc73bb0b
commit
b08154b0ed
|
@ -15,28 +15,50 @@ import java.util.Arrays;
|
|||
*/
|
||||
public class Num1143 {
|
||||
|
||||
private char[] chars1,chars2;
|
||||
private char[] chars1, chars2;
|
||||
private int[][] memory;
|
||||
|
||||
public int longestCommonSubsequence(String text1, String text2) {
|
||||
chars1=text1.toCharArray();
|
||||
chars2=text2.toCharArray();
|
||||
memory=new int[chars1.length][chars2.length];
|
||||
for(int[] row:memory){
|
||||
Arrays.fill(row,-1);
|
||||
chars1 = text1.toCharArray();
|
||||
chars2 = text2.toCharArray();
|
||||
memory = new int[chars1.length][chars2.length];
|
||||
for (int[] row : memory) {
|
||||
Arrays.fill(row, -1);
|
||||
}
|
||||
return dfs(chars1.length-1,chars2.length-1);
|
||||
return dfs(chars1.length - 1, chars2.length - 1);
|
||||
}
|
||||
private int dfs(int i,int j){
|
||||
if(i<0||j<0){
|
||||
|
||||
private int dfs(int i, int j) {
|
||||
if (i < 0 || j < 0) {
|
||||
return 0;
|
||||
}
|
||||
if(memory[i][j]!=-1){
|
||||
if (memory[i][j] != -1) {
|
||||
return memory[i][j];
|
||||
}
|
||||
if(chars1[i]==chars2[j]){
|
||||
return memory[i][j]=dfs(i-1,j-1)+1;
|
||||
if (chars1[i] == chars2[j]) {
|
||||
return memory[i][j] = dfs(i - 1, j - 1) + 1;
|
||||
}
|
||||
return memory[i][j]=Math.max(dfs(i-1,j),dfs(i,j-1));
|
||||
return memory[i][j] = Math.max(dfs(i - 1, j), dfs(i, j - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* dp解法
|
||||
*
|
||||
* @Author Cool
|
||||
* @Date 21:29 2024/9/28
|
||||
**/
|
||||
public int longestCommonSubsequence1(String text1, String text2) {
|
||||
char[] chars1, chars2;
|
||||
chars1 = text1.toCharArray();
|
||||
chars2 = text2.toCharArray();
|
||||
int n = text1.length();
|
||||
int m = text2.length();
|
||||
int[][] dp = new int[n + 1][m + 1];
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < m; j++) {
|
||||
dp[i + 1][j + 1] = chars1[i] == chars2[j] ? dp[i][j] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue