还是比较头疼这种两个字符串,用二维下标表示状态的题目。
392. 判断子序列
也可以双指针
class Solution {
public:
bool isSubsequence(string s, string t) {
int n1 = s.size(), n2 = t.size();
vector<vector<int>> dp(n1 + 1, vector<int> (n2 + 1));
for (int i = 1; i <= n1; i ++)
{
for (int j = 1; j <= n2; j ++)
{
if (s[i-1] == t[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = dp[i][j-1];
}
}
return dp[n1][n2] == s.size();
}
};
115. 不同的子序列
class Solution {
public:
// 相同时可以选或不选当前下标
int numDistinct(string s, string t) {
int n1 = s.size(), n2 = t.size();
vector<vector<unsigned long long>> dp(n1 + 1, vector<unsigned long long> (n2 + 1));
for (int i = 0; i <= n1; i ++) dp[i][0] = 1;
for (int i = 1; i <= n1; i ++)
{
for (int j = 1; j <= n2; j ++)
{
if (s[i-1] == t[j-1])
{
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}
else
dp[i][j] = dp[i-1][j];
}
}
return dp[n1][n2];
}
};