Posted on

Description

Submission

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int n = s.length();
        vector<vector<int>> dp(n, vector<int>(n, 0));

        // len = 1
        for(int i = 0; i < n; ++i) {
            dp[i][i] = 1;
        }


        for(int len = 2; len <= n; ++len) {
            for(int i = 0; i + len <= n; ++i) {
                int j = i + len - 1;                    
                if(s[i] == s[j]) dp[i][j] = max(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];
    }
};

// dp[i][j]: longest palindrome subsequence length within range i, j

//            i       j
// X X X X X [X X X X X] X X

Leave a Reply

Your email address will not be published. Required fields are marked *