2024/9/29 多维dp 1143. 最长公共子序列 dp解法
This commit is contained in:
parent
e7fc73bb0b
commit
b08154b0ed
|
@ -27,6 +27,7 @@ public class Num1143 {
|
|||
}
|
||||
return dfs(chars1.length - 1, chars2.length - 1);
|
||||
}
|
||||
|
||||
private int dfs(int i, int j) {
|
||||
if (i < 0 || j < 0) {
|
||||
return 0;
|
||||
|
@ -39,4 +40,25 @@ public class Num1143 {
|
|||
}
|
||||
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