1. 程式人生 > >【leetcode】516. Longest Palindromic Subsequence

【leetcode】516. Longest Palindromic Subsequence

pre img res mic ima solution .com 分享 tro

題目如下:

技術分享圖片

解題思路:很經典的動態規劃題目,但是用python會超時,只好用C++了。

代碼如下:

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int dp[1001][1001] = {0};
        int res = 1;
        for (int i = s.length()-1;i >=0;i--){
            for (int j = i+1;j<s.length();j++){
                dp[i][i] = 1;
                
if (s[i] == s[j]){ dp[i][j] = dp[i][j] > dp[i+1][j-1]+2 ? dp[i][j] :dp[i+1][j-1]+2; } else{ dp[i][j] = dp[i][j-1] > dp[i+1][j] ? dp[i][j-1] : dp[i+1][j]; } res = res > dp[i][j] ? res : dp[i][j]; } }
return res; } };

【leetcode】516. Longest Palindromic Subsequence