题目要求:
Given a string S and a string T, count the number of distinct subsequences of T in S.
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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
所以递推式:dp[i][j] = dp[i][j] + (T[i] == S[j] ? dp[i - 1][j - 1] : 0);
以S ="rabbbit"
,T = "rabbit"
为例:
r a b b b i t
1 1 1 1 1 1 1 1
r 0 1 1 1 1 1 1 1
a 0 0 1 1 1 1 1 1
b 0 0 0 1 2 3 3 3
b 0 0 0 0 1 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3
代码:
class Solution {
public:
int numDistinct(string S, string T) {
int m = S.size();
int n = T.size();
int dp[n + 1][m + 1];
memset(dp, 0, sizeof(dp));
for(int i = 0; i <= m; ++i)
dp[0][i] = 1;
// dp[i][j] = dp[i][j] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0);
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j)
{
dp[i][j] = dp[i][j - 1];
if(T[i - 1] == S[j - 1])
dp[i][j] += dp[i - 1][j - 1];
}
return dp[n][m];
}
};