leetcode_c++: Distinct Subsequences(115)

来源:互联网 发布:餐厅预约软件 编辑:程序博客网 时间:2024/06/05 07:59

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.


算法

dp
O(n*m)


http://www.cnblogs.com/higerzhang/p/4133793.html

class Solution {public:    int numDistinct(string S, string T)    {        int lenS = S.size(), lenT = T.size();        if (lenS < lenT) return 0;        if (lenT == 0) return lenS;        int dp[lenS + 1][lenT + 1];        //memset(dp, 0, sizeof(dp));        for (int i = 0; i <= lenS; ++i)            dp[i][0] = 1;        for (int i = 1; i <= lenS; ++i)            for (int j = 1; j <= lenT && j <= i; ++j)            {                if (i == j)                    dp[i][j] = S.substr(0, i) == T.substr(0, j);                else                    if (S[i - 1] != T[j - 1])                        dp[i][j] = dp[i - 1][j];                    else                        dp[i][j] = dp[i - 1][j -1] + dp[i - 1][j];            }        return dp[lenS][lenT];    }};
0 0
原创粉丝点击