DP最后一集
回文子串
leetcode:647. 回文子串
动态规划
代码实现
class Solution {
public:
/*
s[i:j]回文子串个数为dp[i][j]
if(s[i] == s[j]){
if(j-i <= 1) dp[i][j] = true;
else dp[i][j] = dp[i+1][j-1];
}
全部初始化为0
*/
int countSubstrings(string s) {
vector<vector<bool>> dp(s.size(),vector<bool>(s.size(),false));
int count = 0;
for(int i = s.size()-1;i >= 0;i--){
for(int j = i;j < s.size();j++){
if(s[i] == s[j]){
if(j-i <= 1){
dp[i][j] = true;
}else dp[i][j] = dp[i+1][j-1];
}
if(dp[i][j] == true) count++;
// cout<<dp[i][j]<<' ';
}
// cout<<endl;
}
return count;
}
};
最长回文子序列
leetcode:516. 最长回文子序列
动态规划
思路
意义:s[i:j]
字符串最长的回文子序列长度为dp[i][j]
。
需要注意j-i>1
时,dp[i][j] = dp[i+1][j-1] + 2;
是加2!!
s[i]!=s[j]
时,dp[i][j] = max(dp[i+1][j],dp[i][j-1]);
。
代码实现
class Solution {
public:
int longestPalindromeSubseq(string s) {
vector<vector<int>> dp(s.size(),vector<int>(s.size(),0));
int result = 0;
for(int i = s.size()-1;i >= 0;i--){
for(int j = i;j < s.size();j++){
if(s[i] == s[j]){
if(j-i == 0) dp[i][j] = 1;
else if(j-i == 1) dp[i][j] = 2;
else dp[i][j] = dp[i+1][j-1] + 2;
}else{
dp[i][j] = max(dp[i+1][j],dp[i][j-1]);
}
// cout<<dp[i][j]<<' ';
if(dp[i][j] > result) result = dp[i][j];
}
// cout<<endl;
}
return result;
}
};
标签:子串,int,57,60,序列,回文,dp,size
From: https://www.cnblogs.com/tazdingo/p/18102140