1. 程式人生 > >[leetcode]516. Longest Palindromic Subsequence

[leetcode]516. Longest Palindromic Subsequence

[leetcode]516. Longest Palindromic Subsequence


Analysis

完了完了 真的要找不到工作了!!!!!蒼了天了!!!—— [每天刷題並不難0.0]

Given a string s, find the longest palindromic subsequence’s length in s. You may assume that the maximum length of s is 1000.
在這裡插入圖片描述
動歸解決~
dp[i][j]表示s中從i到j的子串中最長迴文串的長度,於是狀態轉移方程為:
如果s[i]=s[j],則dp[i][j] += dp[i+1][j-1]+2;
否則dp[i][j] = max(dp[i+1][j], dp[i][j-1])。

Implement

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        int len = s.size();
        vector<vector<int>> dp(len+1, vector<int>(len+1));
        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+1][j], dp[i][j-1]); } } return dp[0][len-1]; } };