distinct-subsequences

来源:互联网 发布:光响应曲线拟合软件 编辑:程序博客网 时间:2024/05/21 06:51

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”
Return3.

和找零钱问题相似,这类问题又一个共同的特点,首先如果用暴力的想法,首先找到第一个字符匹配的位置,之后计算除第一个字符之后的匹配次数.之后就可以迭代,这个和 兆林芊很相似,用一张一块钱之后所有的组合和用两张一块钱之后所有的组合.这类问题暴力有相似的模型,所以动态规划的模型也是相似的.
用dp[i][j]保存s从0到i中包含的t中0到j的个数.

class Solution {public:    int numDistinct(string S, string T) {        int row=S.size();        int col=T.size();        if(row<=0||col<=0)            return 0;        vector<vector<int>> dp(row,vector<int>(col,0));        if(col>row)            return 0;        if(S[0]==T[0])            dp[0][0]=1;        for(int i=1;i<row;++i)            {            if(S[i]==T[0])                dp[i][0]=dp[i-1][0]+1;            else                dp[i][0]=dp[i-1][0];        }        for(int i=1;i<row;++i)            {            for(int j=1;j<col;++j)                {                if(S[i]==T[j])                    dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; //如果相等两种情况,i和j匹配或者i和j不匹配                else                    dp[i][j]=dp[i-1][j]; //不相等只能用0-i-1中寻找            }        }        return dp[row-1][col-1];    }};
0 0
原创粉丝点击