题目
iven 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中删除某些字符,使S转换为T,求不同的转换方法。
显然需要dp,递归求解必然会超时。
从s[i]开始的序列和从t[j]开始的序列的匹配数num[i][j]的递推公式为:
如果s[i]不等于t[j]则,只能用s[i+1]开始的字符串与t[j]开始的字符串匹配,num[i][j]=num[i+1][j];
如果s[i]等于t[j]则,可以用s[i]匹配t[j],也可以使用s[i+1]开始的字符串与t[j]开始的字符串匹配,num[i][j]=num[i+1][j]+num[i+1][j+1]。
从后向前递推,dp。
代码:
class Solution {
public:
int numDistinct(string S, string T) {
vector<vector<int>> num(S.size()+1,vector<int>(T.size()+1,0)); //num[i][j]表示从s[i],t[j]开始的子串的匹配数
for(int i=0;i<=S.size();i++) //初始化
num[i][T.size()]=1;
for(int j=T.size()-1;j>=0;j--) //dp
for(int i=S.size()-1;i>=0;i--)
{
num[i][j]=num[i+1][j];
if(S[i]==T[j])
num[i][j]+=num[i+1][j+1];
}
return num[0][0];
}
};