[LeetCode] 516, the longest palindromic sequence

Title Description

Given a string s, to find the longest palindromic sequence. It can be assumed that sthe maximum length 1000.

输入:"bbbab"
输出:4  // 一个可能的最长回文子序列为 "bbbb"。    注意是“子序列”

Problem-solving ideas

General questions subsequence problem, we need to master the routines and Solution: subsequence problem common ideas | longest palindromic sequence .

  • Dynamic Programming (four elements):

    • State represents: dp[i][j]represents sthe first of the icharacter to the second jsub-string consisting of characters, the longest length of palindromic sequence is.

    • State transition equation:

      • If the sfirst icharacter and the jcharacter of the same words:dp[i][j] = dp[i + 1][j - 1] + 2
      • If the sfirst icharacter and jcharacters of different things:dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

      Note: Note traversal direction dp, and ifrom the last character traversing forward, jfrom i + 1the beginning of next traversal, so you can ensure that each sub-questions have been considered good. (Conclusion This transition according to the state transition equation of state Videos FIG readily available)

    • Initialization: dp[i][i] = 1because the longest palindromic sequence is a single character1

    • Return result:dp[0][n - 1]

Reference Code

class Solution {
public:
    int longestPalindromeSubseq(string str) {
        int length = str.size();
        vector<vector<int> > dp(length, vector<int>(length, 0));
        for(int i = 0; i < length; i++)
            dp[i][i] = 1;
        for(int i = length-2; i >= 0; i--){
            for(int j = i+1; j < length; j++){
                if(str[i] == str[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][length-1];
    }
    
};
Published 415 original articles · won praise 603 · Views 150,000 +

Guess you like

Origin blog.csdn.net/ft_sunshine/article/details/104057684