[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.優化

原題連接(點我)spa

解題思路

給兩個字符串S和T, 求在字符串S中刪除某些字符後獲得T。問一共能有多少種刪除方法?
這個題用常規方法超時。.net

得用動態規劃,動態規劃最基本的就是要找到動態規劃方程。
首先記: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);
code

代碼實現

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 )
相關文章
相關標籤/搜索