516. 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”.

Constraints:

• `1 <= s.length <= 1000`
• `s` consists only of lowercase English letters.

/  dp[i + 1][j - 1] + 2                       if (s[i] == s[j])

dp[i][j] =

\  max(dp[i + 1][j], dp[i][j - 1])        if (s[i] != s[j])

``````class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
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 + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
};
``````

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

``````class Solution {
public:
int longestPalindromeSubseq(string s) {
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 i, int j, vector<vector<int>>& memo) {
if (memo[i][j] != -1) return memo[i][j];
if (i > j) return 0;
if (i == j) return 1;
if (s[i] == s[j]) {
memo[i][j] = helper(s, i + 1, j - 1, memo) + 2;
} else {
memo[i][j] = max(helper(s, i + 1, j, memo), helper(s, i, j - 1, memo));
}
return memo[i][j];
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/516

Palindromic Substrings

Longest Palindromic Substring

Count Different Palindromic Subsequences

Longest Common Subsequence

Longest Palindromic Subsequence II

https://leetcode.com/problems/longest-palindromic-subsequence/

https://leetcode.com/problems/longest-palindromic-subsequence/discuss/99101/Straight-forward-Java-DP-solution

https://leetcode.com/problems/longest-palindromic-subsequence/discuss/99158/c-beats-100-dp-solution-on2-time-on-space

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation