欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LintCode 667: Longest Palindromic Subsequence (DP 经典题)

程序员文章站 2022-07-05 13:00:29
...

经典DP题。我们最后需要返回dp[0][len-1],所以两个for loop是下面的代码:

        for (int i = len - 1; i >= 0; --i) {
            cout<<"i="<<i<<endl;
            for (int j = i + 1; j < len; ++j) {

对于输入 “bbbab”, dp[][] 值为:

1 2 3 3 4
0 1 2 2 3
0 0 1 1 3
0 0 0 1 1
0 0 0 0 1

注意下面两种写法不对:
1)
for (int i = 0; i < len - 1; ++i) {
for (int j = i + 1; j < len; ++j) {

It is wrong as dp[0][len - 1] should be the final result.

  1. for (int i = 0; i < len - 1; ++i) {
    for (int j = 0; j < len; ++j) {
    It is wrong as dp[i+1][j] will exceed the boundary.

代码如下:

class Solution {
public:
    /**
     * @param s: the maximum length of s is 1000
     * @return: the longest palindromic subsequence's length
     */
    int longestPalindromeSubseq(string &s) {
        int len = s.size();
        if (len <= 1) return len;
        
        vector<vector<int>> dp(len, vector<int>(len, 0));
        
        for (int i = 0; i < len; ++i) {
            dp[i][i] = 1;
        }
        for (int i = len - 1; i >= 0; --i) {
            for (int j = i + 1; j < len; ++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][len - 1];
    }
};
相关标签: LintCode