题目:
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
.
思路:
思路1:利用递归的算法去做,时间复杂度较高。 思路2:利用动态规划去做,我们用dp[i][j]表示S与T的前i个字符与前j个字符的匹配子串个数。可以知道: 1)初始条件:T为空字符串时,S为任意字符串都能匹配一次,所以dp[i][0]=1;S为空字符串,S不为空时,不能匹配,所以dp[0][j](j>1)=0。 2)若S的第i个字符等于T的第j个字符时,我们有两种匹配的选择:其一,若S的i-1字符匹配T的j-1字符,我们可以选择S的i字符与T的j字符匹配;其二,若S的i-1字符子串已经能与T的j字符匹配,放弃S的i字符与T的j字符。因此这个情况下,dp[i][j]=dp[i-1][j-1]+dp[i-1][j]。 3)若S的第i个字符不等于T的第j个字符时,这时只有当S的i-1字符子串已经能与T的j字符匹配,该子串能够匹配。因此这个情况下,dp[i][j]=dp[i-1][j]。 思路3:另一种动态规划的方法,自己看看吧
代码:
思路1:
class Solution {
public:
string S;
string T;
int i;
int j;
int count;
int numDistinct(string S, string T) {
this->S = S;
this->T = T;
int i=0;
int j=0;
count =0;
countDistinct();
return count;
}
void countDistinct()
{
if(i>=S.size()&&j>=T.size())
{
count++;
}
else if(i>=S.size())
{
return;
}
else if(j>=T.size())
{
return;
}
else
{
if(S[i]==T[j])
{
i++;
j++;
countDistinct();
j--;
countDistinct();
i--;
}
else
{
i++;
countDistinct();
i--;
}
}
}
};
思路2:
class Solution {
public:
int** dp;
int numDistinct(string S, string T) {
if(S.size()<T.size())
{
return 0;
}
int** dp= new int*[S.size()+1];
for(int k=0;k<=S.size();k++)
{
dp[k]= new int[T.size()+1];
}
for(int i=0;i<=S.size();i++)
{
dp[i][0]=1;
}
for(int i=1;i<=T.size();i++)
{
dp[0][i]=0;
}
for(int j=1;j<=T.size();j++)
{
for(int i=1;i<=S.size();i++)
{
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[S.size()][T.size()];
}
};
思路3:
class Solution {
public:
int numDistinct(string S, string T) {
int** dp = new int*[S.size()+1];
for(int i = 0; i < S.size() + 1; i++){
dp[i] = new int[T.size()+1];
}
for(int i = 0; i < S.size() + 1; i++){
dp[i][0] = 0;
}
for(int i = 0; i < T.size() + 1; i++){
dp[0][i] = 0;
}
dp[0][0] = 1;
int sum = 0;
for(int i = 1; i < S.size() + 1; i++){
for(int j = 1; j < T.size() + 1; j++){
if(S[i-1] == T[j-1]){
dp[i][j] = 0;
for(int k = 0; k < i; k++){
dp[i][j] += dp[k][j-1];
}
if(j == T.size()){
sum += dp[i][j];
}
}else{
dp[i][j] = 0;
}
}
}
return sum;
}
};