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
.
思路:
需要注意的是,这里需要使用S来匹配T。dp[i][j]第一个是S的位置,j是T的位置。
利用动态规划去做,我们用dp[i][j]表示S与T的前i个字符与前j个字符的匹配子串个数。可以知道:
动态规划,定义dp[i][j]为字符串i变换到j的变换方法。
如果S[i]==T[j],那么dp[i][j] = dp[i-1][j-1] + dp[i-1][j]。意思是:如果当前S[i]==T[j],那么当前这个字母即可以保留也可以抛弃,所以变换方法等于保留这个字母的变换方法加上不用这个字母的变换方法。
如果S[i]!=T[i],那么dp[i][j] = dp[i-1][j],意思是如果当前字符不等,那么就只能抛弃当前这个字符。
递归公式中用到的dp[0][0] = 1,dp[i][0] = 0(把任意一个字符串变换为一个空串只有一个方法)
int Distinct_sub(string src,string dst)
{
vector<vector<int> > dp(src.size());
int i,j;
for(i=0;i<src.size();i++)
dp[i].assign(dst.size(),0);
if(src[0] == dst[0])
dp[0][0] =1;
for(j=1;j<dp.size();j++)
dp[j][0] = src[j]==dst[0]? dp[j-1][0]+1:dp[j-1][0];
for(i=1;i<dp.size();i++)
{
for(j=1;j<dp[0].size();j++)
{
if(src[i] == dst[j])
// dp[i][j] = dp[i-1][j-1]>dp[i-1][j]+1?dp[i-1][j-1]:dp[i-1][j]+1; 注意这里 刚开始不知道咋思考的
dp[i][j] = dp[i-1][j-1]+dp[i-1][j];
else
dp[i][j] = dp[i-1][j];
}
}
return dp[src.size()-1][dst.size()-1];
}
int main()
{
string src("rabbbit");
string dst("rabbit");
cout<<Distinct_sub(src,dst)<<endl;
return 0;
}