class Solution {
public:
int numDistinct(string s, string t) {
/*
dp[i][j] : 在0~i-1的s子序列中出现以j-1为结尾的t的个数为dp[i][j]
dp[i][j] =
if s[i - 1] = t[j - 1] :
1.选s[i - 1]进行匹配 -> dp[i - 1][j - 1];
2.不选s[i - 1]进行匹配 -> dp[i - 1][j];
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
else dp[i][j] = dp[i - 1][j];
*/
const long long mod = 10e+9 + 7; //用long long,否则溢出
vector<vector<long long>> dp(s.size()+1, vector<long long>(t.size()+1));
//初始化,dp[0][0] = 1, dp[0][j] = 0, dp[i][0] = 1;
for(int i = 0; i < s.size(); i ++) dp[i][0] = 1;
for(int j = 1; j < t.size(); j ++) dp[0][j] = 0;
for(int i = 1; i <= s.size(); i ++){
for(int j = 1; j <= t.size(); j ++){
if(s[i - 1] == t[j - 1]) dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % mod;
else dp[i][j] = dp[i - 1][j] % mod;
}
}
return dp[s.size()][t.size()];
}
};
<Talk is cheap, show me the code 31> LeetCode.115 不同的子序列
最新推荐文章于 2024-08-22 17:27:46 发布