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.
返回值是3的原因是:rabbit在rabbbit中有三个子序列,分别是删掉rabbbit第一个、第二个、第三个b得到的。
解题思路如下:
动态规划,
定义dp[i][j]为字符串i变换到j的变换方法。
dp[i][0] = 1(把任意一个字符串变换为一个空串只有一个方法,删除所有的字符)
1.若S[i]!=T[j],那么dp[i][j] = dp[i-1][j]
2.若S[i]==T[j],那么dp[i][j] = dp[i-1][j-1] + dp[i-1][j]。当前这个字母即可以保留也可以抛弃,所以变换方法等于保留这个字母的变换方法加上不用这个字母的变换方法。
class Solution {
public:
int numDistinct(string S, string T) {
int size1=S.size();
int size2=T.size();
if(size1==0&&size2==0)
return 0;
if(size1<size2)
return 0;
int **c=new int*[size1+1];
for(int i=0;i<=size1;i++){
c[i]=new int[size2+1];
}
c[0][0]=1;
for(int i=1;i<=size1;i++){
c[i][0]=1;
}
for(int i=1;i<=size2;i++){
c[0][i]=0;
}
for(int i=1;i<=size1;i++){
for(int j=1;j<=size2;j++){
if(S[i-1]==T[j-1])
c[i][j]=c[i-1][j]+c[i-1][j-1];
else
c[i][j]=c[i-1][j];
}
}
return c[size1][size2];
}
};