https://leetcode.com/problems/longest-palindromic-subsequence/
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "bbbab"Output: 4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: "cbbd"Output: 2
One possible longest palindromic subsequence is "bb".
DP:
class Solution {
public:
int longestPalindromeSubseq(string s) {
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
vector<vector<int>> dp(s.size(), vector<int>(s.size(), 0));
dp[0][0] = 1;
for(int i = 1; i < s.size(); ++i){
dp[i][i] = 1;
if(s[i-1] == s[i]) dp[i-1][i] = 2;
else dp[i-1][i] = 1;
for(int j = i-2; j >= 0; --j){
dp[j][i] = max(dp[j][i-1], dp[j+1][i]);
if(s[j] == s[i]) dp[j][i] = max(dp[j][i], dp[j+1][i-1]+2);
}
}
return dp[0][s.size()-1];
}
};
优化了的DP:
class Solution {
public:
int longestPalindromeSubseq(string s) {
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
vector<int> dp(s.size(),0);
int pre, cur;
dp[0] = 1;
for(int i = 0; i < s.size(); ++i){
dp[i] = 1;
pre = 0;
for(int j = i-1; j >= 0; --j){
cur = dp[j];
if(s[j] == s[i]) dp[j] = 2+pre;
else dp[j] = max(dp[j], dp[j+1]);
pre = cur;
}
}
return dp[0];
}
};