从左下往右上遍历
647. 回文子串
class Solution {
public:
// 当s[i] == s[j]时:
// if j - i <= 1 : dp[i][j] = true;
// else if dp[i+1][j-1] : dp[i][j] = true;
// 需要从左下推出右上
int countSubstrings(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
int res = 0;
for (int i = n - 1; i >= 0; i --)
{
for (int j = i; j < n; j ++)
{
if (s[i] == s[j])
{
if (j - i <= 1)
{
res ++;
dp[i][j] = true;
}
else if (dp[i+1][j-1])
{
res ++;
dp[i][j] = true;
}
}
}
}
return res;
}
};
516. 最长回文子序列
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
for (int i = n-1; i >= 0; i --)
{
for (int j = i; j < n; j ++)
{
if (s[i] == s[j])
{
if (j - i <= 1)
{
dp[i][j] = j - i + 1;
}
else
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][n-1];
}
};