LeetCode-516:最長迴文子序列
給定一個字符串s,找到其中最長的迴文子序列。可以假設s的最大長度爲1000。
示例 1:
輸入: "bbbab"
輸出: 4
一個可能的最長迴文子序列爲 "bbbb"。
示例 2:
輸入:"cbbd"
輸出: 2
一個可能的最長迴文子序列爲 "bb"。
思路:
dp[i][j]表示s[i..j]代表的字符串的最長迴文子序列;
d[i][i]=1;
1. 記憶化搜索解法:
int[][] dp;
public int longestPalindromeSubseq(String s) {
int len = s.length();
char[] chs = s.toCharArray();
dp = new int[len][len];
for(int i = 0;i < len;i++)
dp[i][i] = 1;
return longestPalindromeSubseq(chs,0,len-1);
}
public int longestPalindromeSubseq(char[] chs,int i,int j) {
if(i > j || i == chs.length || j == -1)
return 0;
if(dp[i][j] != 0)
return dp[i][j];
if(chs[i] == chs[j])
dp[i][j] = longestPalindromeSubseq(chs,i+1,j-1) + 2;
else
dp[i][j] = Math.max(longestPalindromeSubseq(chs,i+1,j),longestPalindromeSubseq(chs,i,j-1));
return dp[i][j];
}
2. 動態規劃解法:
public int longestPalindromeSubseq(String s) {
int len = s.length();
char[] chs = s.toCharArray();
int[][] dp = new int[len][len];
for(int i = len-1;i >= 0;i--){
dp[i][i] = 1;
for(int j = i+1;j < len;j++){
if(chs[i] == chs[j])
dp[i][j] = dp[i+1][j-1] + 2;
else
dp[i][j] = Math.max(dp[i+1][j],dp[i][j-1]);
}
}
return dp[0][len-1];
}