127_leetcode_Distinct Subsequences

来源:互联网 发布:医学专业翻译软件 编辑:程序博客网 时间:2024/06/06 09:37

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.

1:注意特殊情况;2:设置二维数组保存个数;3:如果T是空串,则返回1;4:动态规划获得相应的个数

    int numDistinct(string S, string T)    {        if(T.size() == 0)        {            return 1;        }        if(S.size() == 0 || T.size() > S.size())        {            return 0;        }                int rows = (int)T.length() + 1;        int columns = (int)S.length() + 1;                vector<vector<int> > result(rows, vector<int>(columns, 0));                for(int i = 0; i < rows; i++)        {            for(int j = 0; j < columns; j++)            {                             if(i == 0)                {                    result[i][j] = 1;                }                else if(j == 0)                {                    result[i][j] = 0;                }                else                {                    result[i][j] = result[i][j-1];                    if(T[i-1] == S[j-1])                    {                        result[i][j] += result[i-1][j-1];                    }                }            }        }                return result[rows-1][columns-1];            }


0 0