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 =
Return S =
"rabbbit"
, T = "rabbit"
3
.Solution1: Normal DP
int numDistinct(string S, string T) {
vector<int> v1(S.size()+1,0);
vector<vector<int>> v2(T.size()+1,v1);
if(S.size() < T.size()) return 0;
for(int i=0;i<=S.size();i++)
v2[0][i]=1;
for(int i=1; i<= T.size(); i++)
for(int j =1; j<=S.size(); j++)
if(S[j-1] == T[i-1])
v2[i][j]=v2[i-1][j-1]+ v2[i][j-1];
else
v2[i][j]=v2[i][j-1];
return v2[T.size()][S.size()];
}
Solution 2: Use reused array
int numDistinct(string S, string T)
{
vector<int> DP(T.size()+1,0);
if(S.size() < T.size()) return 0;
DP[0] = 1;
for(int i=1; i<= S.size(); i ++)
for(int j =T.size(); j>=1; j--)
if(S[i-1] == T[j-1])
DP[j]+= DP [j-1];
return match[T.size()];
}
No comments:
Post a Comment