[LeetCode] Distinct Subsequences [29]

题目

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。问一共能有多少种删除方法?
这个题用常规方法超时。

得用动态规划,动态规划最基本的就是要找到动态规划方程。
首先记:dp[i][j] 为 从S[0..j-1]中删除某些字符后得 T[0...i-1]的不同删除方法数量。
动态规划方程为: dp[i][j] = dp[i][j-1] + (S[j-1]==T[i-1] ? dp[i-1][j-1] : 0);

代码实现

class Solution {
public:
    int numDistinct(string S, string T) {
        int m = S.size();
        int n = T.size();
        if(m<n) return 0;
        vector<vector<int> > dp(n+1, vector<int>(m+1, 0));
        for(int i=0; i<m; ++i)
            dp[0][i] = 1;
        for(int i=1; i<=n; ++i){
            for(int j=1; j<=m; ++j){
                dp[i][j] = dp[i][j-1] + (S[j-1]==T[i-1] ? dp[i-1][j-1] : 0);
            }
        }
        return dp[n][m];
    }
};

对于辅助数组我们其有用到的也仅仅有当前行和其前一行。所以我们能够仅仅申请两行的辅助数组。优化代码例如以下:

class Solution {
public:
    int numDistinct(string S, string T) {
        int m = S.size();
        int n = T.size();
        if(m<n) return 0;
        vector<int> dp1(m+1, 1);
        vector<int> dp2(m+1, 0);        
        for(int i=1; i<=n; ++i){
            for(int j=1; j<=m; ++j){
                dp2[j] = dp2[j-1] + (S[j-1]==T[i-1] ? dp1[j-1] : 0);
            }
            dp1.clear();
            dp1 = dp2;
            dp2[0] = 0;
        }
        return dp1[m];
    }
};

假设你认为本篇对你有收获,请帮顶。
另外。我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你能够搜索公众号:swalge 或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/30043797 )

原文地址:https://www.cnblogs.com/zhchoutai/p/6714751.html