LeetCode: Distinct Subsequences

来源:互联网 发布:mac姨妈色口红 编辑:程序博客网 时间:2024/06/05 05:24

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.

class Solution {public:    int numDistinct(string S, string T) {        int sizeS = S.size();        int sizeT = T.size();        int temp[sizeS+1][sizeT+1];        for(int i = 0; i <= sizeT; i++)        {            temp[0][i] = 0;            }        for(int i = 0; i <= sizeS; i++)        {            temp[i][0] = 1;            }        for(int i = 1; i <= sizeS; i ++)        {            for(int j = 1; j <= sizeT; j++)            {                if(S[i-1] == T[j-1])                    temp[i][j] = temp[i-1][j-1] + temp[i-1][j];                else                    temp[i][j] = temp[i-1][j];            }        }        return temp[sizeS][sizeT];            }};

Round 2:

class Solution {public:    int numDistinct(string S, string T) {if(S.size() < T.size())return 0;int **count = (int **)calloc(T.size()+1, sizeof(int*));for(int i = 0; i <= T.size(); i++)count[i] = (int *)calloc(S.size() + 1, sizeof(int));//memset(count, 0, (T.size() + 1) * (S.size() + 1) * sizeof(int));for(int i = 0; i <= T.size(); i++){for(int j = i; j <= S.size(); j++){if(i == 0)count[i][j] = 1;else{if(T[i-1] == S[j-1])count[i][j] = count[i-1][j-1] + count[i][j-1];elsecount[i][j] = count[i][j-1];}}}return count[T.size()][S.size()];    }};


0 0