2024/9/29 多维dp 1143. 最长公共子序列 dp解法

This commit is contained in:
Cool 2024-09-29 23:30:30 +08:00
parent e7fc73bb0b
commit b08154b0ed
1 changed files with 35 additions and 13 deletions

View File

@ -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];
}
}