Leetcode #516. Longest Palindromic Subsequence

Leetcode #516. Longest Palindromic Subsequence

题目

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

代码

比较典型的动态规划问题。递归写了一遍TLE了,循环方法没有问题。

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int ** dp = new int * [s.length()];
        for (int i = 0; i < s.length(); i++) {
            dp[i] = new int [s.length()];
            memset(dp[i], 0, sizeof(int) * s.length());
            dp[i][i] = 1;
        }


        for (int g = 2; g <= s.length(); g++) {
            for (int i = 0; i + g - 1 < s.length(); i++) {
                if (s[i] == s[i + g - 1]) dp[i][i + g - 1] = dp[i + 1][i + g - 2] + 2;
                else dp[i][i + g - 1] = max(dp[i + 1][i + g - 1], dp[i][i + g - 2]);
            }
        }
        int ret = dp[0][s.length() - 1];
        for (int i = 0; i < s.length(); i++)
            delete [] dp[i];
        return ret;
    }

};
点赞