最长回文子序列
学习记录自代码随想录
要点:1.dp数组定义为:dp[i][j]为区间是s[i:j]内最长回文子序列;
2.递推公式: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])
3.dp数组初始化dp[i][i] = 1, 其余为0
4.遍历顺序:for(int i = n-2; i >= 0; i--)
for(int j = i+1; j < n; j++)
cpp
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
// 1.dp[i][j] 区间s[i:j]内最长的回文子序列长度
vector<vector<int>> dp(n, vector<int>(n, 0));
// 2.递推公式: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])
// 3.初始化:dp[i][i] = 1;
for(int i = 0; i < n; i++) dp[i][i] = 1;
// 4.遍历顺序:i+1->i, j-1->j
for(int i = n-2; i >= 0; i--){
for(int j = i+1; j < n; 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]);
}
}
// 5.举例推导dp数组
return dp[0][n-1];
}
};