115. Distinct Subsequences
Hard
54125FavoriteShare
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
class Solution {
public:
int numDistinct(string s, string t)
{
//边界条件
if(t.length()>s.length())return 0;
if(t.size()==0)return 1;
int ans=0;
//动态规划 前x个字母中 前y个字母出现的个数
//从栈分配必须用常量初始化 否则动态分配
int **dp=new int*[s.size()+1];//每一行初始化
for(int i=0;i<s.size()+1;i++)//每一列初始化
{
dp[i]=new int[t.size()+1];
memset(dp[i], 0, sizeof(int)*(t.size()+1));
}
//memset(dp[0], 0, sizeof(int)*(t.size()+1));
dp[0][0]=1;
for(int i=1;i<t.size();i++)
{
dp[0][i]=0;
}
for(int i=1;i<s.size();i++)
{
dp[i][0]=1;
}
for(int i=1;i<=s.size();i++)
{
for(int j=1;j<=t.size();j++)
{
if(j>i)
{
dp[i][j]=0;
}
else
{
dp[i][j]=dp[i-1][j];//s变长了 结果至少和s变长之前一样
if(s[i-1]==t[j-1])
{
//如果最后的字符一致 除了dp[i][j]=dp[i-1][j]的字串之外 让最后两个字符保持一致 其他还要加加的数量是
dp[i][j]+=dp[i-1][j-1];
}
//cout<<"dp["<<i<<"]"<<"["<<j<<"]"<<dp[i][j]<<endl;
}
}
}
ans=dp[s.size()][t.size()];//delete之前赋值
//防止内存泄漏
/*
for(int i=0;i<s.size()+1;i++)
{
delete []dp[i];
dp[i]=NULL;
}
delete []dp;
dp=NULL;
*/
return ans;
}
};