Leetcode 516. Longest Palindromic Subsequence 最长回文子序列斜着动态规划

  • dp[i][j] i…j的序列中,最长回文子序列的值
  • 可将图画出,发现斜着动归
  • 状态转移:无非就是 d p [ i ] [ j ] dp[i][j] dp[i][j]
    • d p [ i ± 1 ] [ j ± 1 ] dp[i\pm1][j\pm1] dp[i±1][j±1]
    • d p [ i ± 1 ] [ j ] dp[i\pm1][j] dp[i±1][j]
    • d p [ i ] [ j ± 1 ] dp[i][j\pm1] dp[i][j±1]
    • 具体看动态规划的方向。实在没思路就先把它们写下来或者画出来,强行找关系
class Solution {
public:
    int longestPalindromeSubseq(string s) {
        vector<vector<int>> dp(s.length(), vector<int>(s.length(), 0));
        for(int i=0; i<s.length(); i++)
            dp[i][i] = 1;
        for(int i=s.length()-1; i>=0; i--)
            for(int j=i+1; j<s.length(); j++){
                if(s.at(i) == s.at(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][s.length()-1];
    }
};

你可能感兴趣的:(算法,算法,动态规划,最长回文子序列)