题目链接:516. 最长回文子序列
递归版本(会超时):
public class Code7_PalindromeSubsequence {
public static int PalindromeSubsequence1(String str) {
char[] _str = str.toCharArray();
return process(_str, 0, _str.length);
}
public static int process(char[] str, int L, int R) {
if (L == R) {
return 1;
}
if (L == R - 1) {
return str[L] == str[R] ? 2 : 1;
}
int p1 = process(str, L + 1, R);
int p2 = process(str, L, R - 1);
int p3 = process(str, L + 1, R - 1);
int p4 = str[L] == str[R] ? (2 + process(str, L + 1, R - 1)) : 0;
return Math.max(Math.max(p1, p2), Math.max(p3, p4));
}
}
动态规划版本(最优解):
public class Code7_PalindromeSubsequence {
public static int PalindromeSubsequence2(String str) {
char[] _str = str.toCharArray();
int N = _str.length;
int[][] dp = new int[N][N];
dp[N - 1][N - 1] = 1;
for (int i = 0; i < N - 1; i++) {
dp[i][i] = 1;// 对角线全为1
dp[i][i + 1] = _str[i] == _str[i + 1] ? 2 : 1;
}
for (int L = N - 3; L >= 0; L--) {
for (int R = L + 2; R < N; R++) {
dp[L][R] = Math.max(dp[L][R - 1], dp[L + 1][R]);
if (_str[L] == _str[R]) {
dp[L][R] = Math.max(dp[L][R], dp[L + 1][R - 1] + 2);
}
}
}
return dp[0][N - 1];
}
}