下面提供了两种思路
- 第一种是递归的思想,提交到平台上会超时
- 第二种是经典dp思想,不会超时,第二种解法是从第一种递归解法的基础上得到的
递归代码:
package com.dp;
//链接:https://leetcode.com/problems/longest-common-subsequence/
public class Code5_LongestCommonSubsequence {
public int longestCommonSubsequence1(String text1, String text2) {
return process1(text1.toCharArray(), text2.toCharArray(), text1.length() - 1, text2.length() - 1);
}
public int process1(char[] str1, char[] str2, int i, int j) {
if (i == 0 && j == 0) {
return str1[i] == str2[j] ? 1 : 0;
} else if (i == 0) {
if (str1[i] == str2[j]) {
return 1;
} else {
return process1(str1, str2, i, j - 1);
}
} else if (j == 0) {
if (str1[i] == str2[j]) {
return 1;
} else {
return process1(str1, str2, i - 1, j);
}
} else {
int p1 = process1(str1, str2, i - 1, j);// 最长公共子序列有可能以j结尾,但是必定不以i结尾
int p2 = process1(str1, str2, i, j - 1);// 最长公共子序列有可能以i结尾,但是必定不以j结尾
int p3 = str1[i] == str2[j] ? 0 : 1 + process1(str1, str2, i - 1, j - 1);// 最长公共子序列不以i结尾也不以j结尾
return Math.max(p1, Math.max(p2, p3));
}
}
}
经典dp代码:
package com.dp;
//链接:https://leetcode.com/problems/longest-common-subsequence/
public class Code5_LongestCommonSubsequence {
public int longestCommonSubsequence2(String text1, String text2) {
char[] str1 = text1.toCharArray();
char[] str2 = text2.toCharArray();
int N = str1.length;
int M = str2.length;
int[][] dp = new int[N][M];
dp[0][0] = str1[0] == str2[0] ? 1 : 0;
for (int j = 1; j < M; j++) {
dp[0][j] = str1[0] == str2[j] ? 1 : dp[0][j - 1];
}
for (int i = 1; i < N; i++) {
dp[i][0] = str1[i] == str2[0] ? 1 : dp[i - 1][0];
}
for (int i = 1; i < N; i++) {
for (int j = 1; j < M; j++) {
int p1 = dp[i - 1][j];// 最长公共子序列有可能以j结尾,但是必定不以i结尾
int p2 = dp[i][j - 1];// 最长公共子序列有可能以i结尾,但是必定不以j结尾
int p3 = str1[i] == str2[j] ? 1 + dp[i - 1][j - 1] : 0;// 最长公共子序列不以i结尾也不以j结尾
dp[i][j] = Math.max(p1, Math.max(p2, p3));
}
}
return dp[N - 1][M - 1];
}
}