LeetCode-Distinct Subsequences

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只通过删除操作进行变换的方法数(通过从S中删去几个字符变成T的方法)

通过动归,对S前i位与T前j位的情况 考虑均新增一位会如何变化

class Solution {
public:
    int numDistinct(string S, string T) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<int> > count;
        if(S.length()<T.length())return 0;
        count.resize(S.length()+1);
        for(int i=0;i<=S.length();i++){
            count[i].resize( min(i,(int)T.length()) +1);
            count[i][0]=1;
        }
        for(int i=1;i<=S.length();i++)
        {
            if(count[i].size()==i+1){
                int j=1;
                for(;j<count[i].size()-1;j++){
                    if(S[i-1]==T[j-1]){
                        count[i][j]=count[i-1][j-1]+count[i-1][j];
                    }
                    else{
                        count[i][j]=count[i-1][j];
                    }
                }
                if(S[i-1]==T[j-1]){
                    count[i][j]=count[i-1][j-1];
                }
                else{
                    count[i][j]=0;
                }
            }
            else{
                int j=1;
                for(;j<count[i].size();j++){
                    if(S[i-1]==T[j-1]){
                        count[i][j]=count[i-1][j-1]+count[i-1][j];
                    }
                    else{
                        count[i][j]=count[i-1][j];
                    }
                }
            }
        }
        return count[S.length()][T.length()];
    }
};
View Code

 

posted @ 2013-10-09 00:16  懒猫欣  阅读(177)  评论(0编辑  收藏  举报