LeetCode 0115 - Distinct Subsequences
# Hints
- DP
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Hard |
Given two strings and , return the number of distinct subsequences of which equals .
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from s.
rabbbit
rabbbit
rabbbit
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from s.
babgbag babgbag babgbag babgbag babgbag
Constraints:
and consist of English letters.
# 题意
给定两个字符串 和 ,求 中有多少个位置不同的子序列与 相同。
# 题解
为便于描述,设字符串的下标从 起,字符串 和 的长度分别为 和 。
考虑动态规划,设 表示 中 的出现次数,状态转移方程为:
则 即为答案。时间复杂度为 。
# AC代码
class Solution {
public:
int numDistinct(const string & s, const string & t) {
// 初始化
int n = s.length(), m = t.length();
int dp[n + 1][m + 1];
memset(dp, 0, sizeof(dp));
int mod = 1e9 + 7;
// 递推
for (int i = 0; i <= n; i ++) {
dp[i][0] = 1;
}
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= i && j <= m; j ++) {
if (s[i - 1] == t[j - 1]) {
dp[i][j] = dp[i - 1][j] % mod + dp[i - 1][j - 1] % mod;
} else {
dp[i][j] = dp[i - 1][j] % mod;
}
}
}
// 返回
return dp[n][m];
}
};
- 03
- Linux 00 - Introduction02-01