【Hard 递归 动态规划 回文串15】LeetCode 730. Count Different Palindromic Subsequences
程序员文章站
2022-07-15 11:13:50
...
LeetCode 730. Count Different Palindromic Subsequences
博客转载自:http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-730-count-different-palindromic-subsequences/
博主 花花酱。讲解的生动又形象!
Solution1:递归
class Solution { //递归
public:
int countPalindromicSubsequences(string S) {
int n = S.size();
m_ = vector<vector<int> >(n + 1, vector<int>(n + 1, 0));
return count(S, 0, n - 1);
}
private:
static constexpr long KMod = 1000000007;
long count(string& s, int begin, int end) {
if (begin > end) return 0;
else if (begin == end) return 1;
if (m_[begin][end] > 0) return m_[begin][end];
long sum = 0;
if (s[begin] == s[end]) {
int l = begin + 1, r = end - 1;
while (l <= r && s[l] != s[begin]) ++l;
while (l <= r && s[r] != s[begin]) --r;
if (l > r)
sum = 2 * count(s, begin + 1, end - 1) + 2;
else if (l == r)
sum = 2 * count(s, begin + 1, end - 1) + 1;
else
sum = 2 * count(s, begin + 1, end - 1) - count(s, l + 1, r - 1);
} else
sum = count(s, begin, end - 1) + count(s, begin + 1, end) - count(s, begin + 1, end - 1);
m_[begin][end] = (sum + KMod) % KMod;//为了避免余数出现负数的方法
return m_[begin][end];
}
vector<vector<int> > m_;
};
Solution2:
动态规划:通过长度来维护数组
注意:在维护动态数组时,要确保使用的动态数组元素是已经维护过的
class Solution {
public:
int countPalindromicSubsequences(const string& S) {
int n = S.length();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i)
dp[i][i] = 1;
//通过长度来维护递归数组
for (int len = 1; len <= n; ++len) {//len指的是首尾索引之差,非真正的字符串长短
for (int i = 0; i < n - len; ++i) {
const int j = i + len;
if (S[i] == S[j]) {
dp[i][j] = dp[i + 1][j - 1] * 2;
int l = i + 1;
int r = j - 1;
while (l <= r && S[l] != S[i]) ++l;
while (l <= r && S[r] != S[i]) --r;
if (l == r) dp[i][j] += 1;
else if (l > r) dp[i][j] += 2;
else dp[i][j] -= dp[l + 1][r - 1];
} else {
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
}
dp[i][j] = (dp[i][j] + kMod) % kMod;
}
}
return dp[0][n - 1];
}
private:
static constexpr long kMod = 1000000007;
};