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"
Return3
利用动态规划:dp[i][j] 表示S[0:i] 删除若干元素得到 T[0:j]的 情况总数
r a b b i t
1 0 0 0 0 0 0
r 1
a 1
b 1
b 1
b 1
i 1
t 1
边界条件:
当i=0时,即S为空串,只有当T为空串时,可以由S得到T(dp[0][0]=1),否则无法由S得到T(dp[0][j] = 0)
当j=0时,即T为空串,无论S为何种串,只要将S中的元素全删除就可以得到T,因此,此种一种办法 即dp[i][0]=1
考虑其他问题 当S[0:i] 得到 T[0:j] 求dp[i][j]
1)S[i] = T[j] : 可以从dp[i-1][j-1]到达dp[i][j] ,同时也可以由dp[i-1][j]到达dp[i][j] 这时只需要将S[i]删除即可
因此dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
2) S[i] != T[j] : dp[i-1][j]到达dp[i][j] ,需要将S[i]删除即可
int numDistinct(string S, string T) {
int lenS = S.length();
int lenT = T.length();
vector<vector<int>> dp(lenS+1,vector<int>(lenT+1,0));
//dp[i][j] S[0:i] match T[0:j]
//i=0 S为空串
for(int i=0; i<lenT+1; ++i)
dp[0][i]=0;
//j=0 T为空串
for(int i=0; i<lenS+1; ++i)
dp[i][0]=1;
for(int i=1;i<lenS+1;++i)
{
for(int j=1;j<lenT+1;++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[lenS][lenT];
}