文档链接:https://programmercarl.com/
LeetCode392.判断子序列
题目链接:https://leetcode.cn/problems/is-subsequence/
思路:自己AC的,一直困在二维数组的遍历中
动规:
class Solution {
public:
bool isSubsequence(string s, string t) {
vector<vector<bool>> dp(t.size() + 1, vector<bool>(s.size() + 1, false));
for(int i = 0; i <= t.size(); i++) dp[i][0] = true;
for(int j = 1; j <= s.size(); j++) {
for(int i = 1; i <= t.size(); i++) {
if(t[i - 1] == s[j - 1]) dp[i][j] = dp[i - 1][j - 1];
else dp[i][j] = dp[i - 1][j];
}
}
return dp[t.size()][s.size()];
}
};
LeetCode115.不同的子序列
题目链接:https://leetcode.cn/problems/distinct-subsequences/
思路:这题包括上题都没有太明确dp数组的含义,而是把二维数组画出来自然而然就能写出递推公式了,有时候我觉得不用陷入模板太深也未尝不可。
动规:
class Solution {
public:
int numDistinct(string s, string t) {
vector<vector<unsigned long long>> dp(t.size() + 1, vector<unsigned long long>(s.size() + 1, 0));
for(int j = 0; j <= s.size(); j++) dp[0][j] = 1;
for(int i = 1; i <= t.size(); i++) {
for(int j = 1; j <= s.size(); j++) {
if(s[j - 1] == t[i - 1]) dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1];
else dp[i][j] = dp[i][j - 1];
}
}
return dp[t.size()][s.size()];
}
};
总结:跟着感觉走!