516. Longest Palindromic Subsequence

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

Constraints:

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

算法思路:

  • 说明:一道很明显的动态规划问题,因为对于自序列的最大回文自序列,对于每一个位置都有出现或者不出现的选项,因此有2^n个子序列(从这就可以得出必用dp),然后分别判断每一个子序列是否是回文的,使用这种暴力显然是还不可取的;
  • 定义:本题动态规划的思想也很简单,对于[0, right]区间,right不断的增加1,然后内部循环left由right不断移向0,不断更新dp[left][right]的值,dp[left][right],区间[left, right]最长回文子序列的长度;
  • 状态转移方程:dp[left][right] = dp[left + 1][right - 1] + 2,if s[left] == s[right],                                                                                                   else dp[left][right] = max(dp[left][right - 1], dp[left -1][right]);
  • 初始条件:dp[right][right] = 1;
  • 结果:dp[0][n - 1]。
class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int n = s.size();
        vector> dp(n, vector(n));
        
        for(int right = 0; right < n; right++) {
            dp[right][right] = 1;
            for(int left = right - 1; left >= 0; left--) {
                if(s[left] == s[right]) {
                    dp[left][right] = dp[left + 1][right - 1] + 2;
                } else {
                    dp[left][right] = max(dp[left + 1][right], dp[left][right - 1]);
                }
            }
        }
        
        return dp[0][n - 1];
    }
};

 

你可能感兴趣的:(leetcode)