516. Longest Palindromic Subsequence
Problem statement:
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".
Solution:
This is a dynamic programming problem. The key point also is to find the dynamic formula. Although there is only one string, but we need a two dimension array. The value in diagonal is 1 and we only need right up part above diagonal.
dp[i][j] means the max subsequence from position i to j. The formula is:
dp[i][j] = dp[i + 1][j - 1] if s[i] == s[j]
= max(dp[i + 1][j], dp[i][j + 1]) if s[i] != s[j]
Since there is i + 1 and j - 1 is essential for current dp[i][j], we should do DP from bottom to up, left to right.
The time complexity is O(n*n), n is the size of string.
class Solution { public: int longestPalindromeSubseq(string s) { int size = s.size(); vector<vector<int>> dp(size, vector<int>(size, 0)); for(int i = 0; i < size; i++){ dp[i][i] = 1; } for(int i = size - 2; i >= 0; i--){ for(int j = i + 1; j < size; j++){ if(s[i] == s[j]){ dp[i][j] = dp[i + 1][j - 1] + 2; } else { dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); } } } return dp[0][size - 1]; } };