Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
One possible longest palindromic subsequence is "bbbb".
One possible longest palindromic subsequence is "bb".
// Bottom-Up Dynamic Programming
int longestPalindromeSubseq(string s) { // time: O(n^2); space: O(n^2)
int n = s.size();
vector<vector<int> > dp(n, vector<int>(n, 0));
for (int j = 0; j < n; ++j) {
dp[j][j] = 1;
for (int i = j - 1; i >= 0; --i) {
if (s[i] == s[j]) {
dp[i][j] = (j - i >= 2 ? dp[i + 1][j - 1] : 0) + 2;
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
// Top-Down Dynamic Programming
int longestPalindromeSubseq(string s) { // time: O(n^2); space: O(n^2)
int n = s.size();
vector<vector<int> > memo(n, vector<int>(n, -1));
return helper(s, 0, n - 1, memo);
}
int helper(string& s, int start, int end, vector<vector<int> >& memo) {
if (memo[start][end] != -1) return memo[start][end];
if (start > end) return 0;
if (start == end) return 1;
if (s[start] == s[end]) memo[start][end] = helper(s, start + 1, end - 1, memo) + 2;
else memo[start][end] = max(helper(s, start + 1, end, memo), helper(s, start, end - 1, memo));
return memo[start][end];
}