难度Hard
原题连接
内容描述
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
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.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
思路 - 时间复杂度: O(n^2)- 空间复杂度: O(n^2)******
这题是一道动态规划的问题,动态问题的关键的就是写出状态转移方程。这里我们定义一个数组 dp[m][n],表示在 s[m] 和 t[n] 之前有几个匹配的子序列,这样我们可以写出状态转移方程 当 s[m] != t[n],dp[m][n] = dp[m - 1][n]。else dp[m][n] += (dp[m - 1][n] + dp[m - 1][n - 1])
class Solution {
public:
int numDistinct(string s, string t) {
int l1 = s.length(),l2 = t.length();
int dp[l1 + 1][l2 + 1];
memset(dp,0,sizeof(dp));
for(int i = 1;i <= l1;++i)
if(s[i - 1] == t[0])
dp[i][1] = 1;
for(int i = 1;i <= l1;++i)
for(int j = 1;j <= l2;++j)
{
if(s[i - 1] != t[j - 1])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] += (dp[i - 1][j - 1] + dp[i - 1][j]);
//cout << dp[i][j] << " ";
}
return dp[l1][l2];
}
};