LeetCode Longest Palindromic Subsequence

LeetCode 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".

```class Solution2 {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = n - 1; i >= 0; --i) {
dp[i][i] = 1;
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j])dp[i][j] = dp[i + 1][j - 1] + 2;
else dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]);
}
}
return dp[0][n - 1];
}
};
```

```class Solution {
private:
int helper(int l, int r, const string &s, vector<vector<int>> &dp) {
if (l > r)return 0;
if (l == r)return 1;
if (dp[l][r] != 0)return dp[l][r];
if (s[l] == s[r])dp[l][r] = helper(l + 1, r - 1, s, dp) + 2;
else dp[l][r] = max(helper(l, r - 1, s, dp), helper(l + 1, r, s, dp));
return dp[l][r];
}
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
return helper(0, n - 1, s, dp);
}
};
```