Title Description
Given a string s
, to find the longest palindromic sequence. It can be assumed that s
the 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]
representss
the first of thei
character to the secondj
sub-string consisting of characters, the longest length of palindromic sequence is. -
State transition equation:
- If the
s
firsti
character and thej
character of the same words:dp[i][j] = dp[i + 1][j - 1] + 2
- If the
s
firsti
character andj
characters of different things:dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
Note: Note traversal direction dp, and
i
from the last character traversing forward,j
fromi + 1
the 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) - If the
-
Initialization:
dp[i][i] = 1
because 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];
}
};