516. The longest palindrome subsequence
status: dp [i] [j] dp[i][j]d p [ i ] [ j ] represents the sequences [i, j] s[i,j]s[i,j ] The length of the longest palindrome subsequence that can be generated.
Time complexity:O (n 2) O(n^2)O ( n2 ) The
large interval depends on its sub-intervals.
DP equation:
dp [i] [j] = max {dp [i] [j − 1], dp [i + 1] [j], dp [i + 1] [j − 1] + 2 ∗ (s [ i] = = s [j])} dp[i][j] = max\{dp[i][j-1],dp[i+1][j],dp[i+1][j- 1]+2*(s[i]==s[j])\}dp[i][j]=max{
dp[i][j−1],dp[i+1][j],dp[i+1][j−1]+2∗(s[i]==s[j])}
class Solution {
public:
int dp[1010][1010] = {
0};
int longestPalindromeSubseq(string s) {
int n = s.size();
s = ' '+s;
for(int i=1;i<=n;i++){
dp[i][i] = 1;
}
for(int j=1;j<=n;j++){
for(int i=j-1;i>=1;i--){
dp[i][j] = max(dp[i+1][j],dp[i][j-1]);
if(s[i]==s[j]) dp[i][j] = max(dp[i][j],dp[i+1][j-1]+2);
}
}
return dp[1][n];
}
};