[Leetcode] Distinct Subsequences

来源:互联网 发布:网络电视iptv设置 编辑:程序博客网 时间:2024/05/04 09:33

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.

比较简单的二维动规,假设distinct[i][j]表示S的前i位和T的前j位的 Distinct Subsequences 个数。

状态方程:

distinct[i][j] = (S[i]==T[j])?distinct[i-1][j]+distinct[i-1][j-1]:distinct[i-1][j] 

要初始化一下边界。

class Solution {public:    int numDistinct(string S, string T) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(S==""||T=="")        {            return 0;        }                vector<vector<int> > distinct (S.size(),vector<int>(T.size()));                for(int i=0;i<S.size();i++)        {            if(T[0]==S[i])            {                distinct[i][0] = (i==0)?1:distinct[i-1][0]+1;            }            else            {                distinct[i][0] = (i==0)?0:distinct[i-1][0];            }        }                for(int i=1;i<T.size();i++)        {            distinct[0][i] = 0;        }                for(int i=1;i<S.size();i++)        {            for(int j=1;j<T.size();j++)            {                if(j>i)//剪枝                {                    distinct[i][j] = 0;                    continue;                }                                if(S[i]==T[j])                {                    distinct[i][j] = distinct[i-1][j] + distinct[i-1][j-1];                }                else                {                    distinct[i][j] = distinct[i-1][j];                }            }        }                return distinct[S.size()-1][T.size()-1];    }};


原创粉丝点击