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
.
方法一:用回溯法实现,时间复杂度很高,空间复杂度低,对于小数据可以通过,对大数据会出现Time Limit Exceeded
int num=;
void countnum(string S, string T) {
if(T.size()==)
{
num++;
return;
} for(int i=; i<S.size(); i++)
{
if(S[i]==T[])
{
string s2 = S.substr(i+);
string t2 = T.substr();
countnum(s2, t2);
} }
return;
} class Solution {
public:
int numDistinct(string S, string T) {
countnum(S, T);
return num;
}
};
方法二:用动态规划(DP)实现,需要的空间复杂度为O(N*M),对于大数据也可以很快处理。
class Solution {
public:
int numDistinct(string S, string T) {
vector<vector<int> > num(S.size()+,vector<int>(T.size()+,)); //num[i][j]表示T中的前j个字符构成的子字符串在S中的前i个字符中出现的次数,num[i][j]满足:
S = " "+ S; //(1)若S[i]=T[j],则num[i][j] = num[i-1][j]+num[i-1][j-1];
T = " "+ T; //(2)若S[i]!=T[j],则num[i][j] = num[i-1][j];
num[][]=; //(3)若j>i,则num[i][j]=0。
for(int i=; i<S.size(); i++)
for(int j=; j<T.size(); j++)
{
if(j>i)
{
num[i][j]=;
break;
}
if(S[i]==T[j])
num[i][j] = num[i-][j] + num[i-][j-];
else
num[i][j] = num[i-][j];
}
return num[S.size()-][T.size()-]; }
};