您的位置:首页 > 产品设计 > UI/UE

Distinct Subsequences leetcode 115

2015-06-09 17:55 351 查看
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串

动态规划,设置一个矩阵ans[i][j]表示由字符串s前i+1个字符能转换成t串前j+1的种数(i,j从0开始)

1,s[0]==t[0]的话,ans[0][0]=1,ans[o][j]=0因为s串长度为1时,并不能转换成t串

2,s[i]=!t[j],ans[i][j]=ans[i-1][j]因为此时字符不相等,该位置能转换成t串的种数就等于s串前i-1位能转换的次数

3,s[i]==t[j],ans[i][j]=ans[i-1][j]+ans[i-1][j-1],表示此时字符相同,则该位置能转换的次数就等于s串不加该相同字符的种数(ans[i-1][j]s串前i位出现的次数前i-1位也一定会出现)加上s串t串都不包含该字符的种数(ans[i-1][j-1]因为该位字符相同,那么如果t串前j-1位能被s串前i-1位转化,那加上该字符也一定能转化,那么种数就要加上不包含这个字符的种数)



class Solution {
public:
int numDistinct(string s, string t) {
if(s.size()==0)return 0;
vector<vector<int>> ans(s.size(),vector<int>(t.size(),0));
if(s[0]==t[0])ans[0][0]=1;
for(int i=1;i<s.size();i++){
for(int j=0;j<t.size();j++){
if(s[i]!=t[j])ans[i][j]=ans[i-1][j];
else ans[i][j]=ans[i-1][j]+(j==0?1:ans[i-1][j-1]);//当j=0时,s[i]==t[0]时,ans[i][j]要加1
}
}
return ans[s.size()-1][t.size()-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string