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.
C++
class Solution {
public:
int numDistinct(string S, string T) {
S=" "+S,T=" "+T;
int n=S.length();
int m=T.length();
int i;
int j;
vector<vector<int> > dp(n+1,vector<int>(m+1,0));
for(i=0;i<=n;i++) dp[i][0]=1;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++){
dp[i][j]=dp[i-1][j];
if(S[i]==T[j]) dp[i][j]+=dp[i-1][j-1];
}
return dp[n][m];
}
};
手机扫一扫
移动阅读更方便
你可能感兴趣的文章