Distinct Subsequences 解題報告,subsequences

來源:互聯網
上載者:User

Distinct Subsequences 解題報告,subsequences

題目:給兩個字串S和T,判斷T在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:遞迴(TLE)

如果當前字元相同,結果加上S和T在該index之後的匹配方法數

如果當前字元不同,將S的指標向後移,遞迴計算

class Solution {private:    int cnt;    int len_s;    int len_t;public:    Solution():cnt(0){}    void Count(string S,string T, int idx_ss, int idx_ts){        if(idx_ts == len_t){            cnt++;            return;        }        int i,j,k;        for (i=idx_ss; i<len_s; i++) {            if (S[i] == T[idx_ts]) {                Count(S, T, i + 1, idx_ts + 1);            }        }    }        int numDistinct(string S, string T) {        len_s = S.length();        len_t = T.length();        Count(S, T, 0, 0);        return cnt;    }};






-----------------------------------------------------




思路2:DP

如果當前字元相同,dp[i][j]結果等於用S[i](dp[i-1][j-1])和不用S[i](dp[i-1][j])方法數求和

如果當前字元不同,dp[i][j] = dp[i-1][j]


class Solution {private:    int len_s;    int len_t;public:    int Count(string S,string T){        int i,j;        int dp[len_s][len_t];        memset(dp, 0, sizeof(dp));                if (S[0]==T[0]) {            dp[0][0] = 1;        }                for(i=1;i<len_s;i++){            dp[i][0] = dp[i-1][0];            if (T[0]==S[i]) {                dp[i][0]++;            }        }                        for (i=1; i<len_s; i++) {            for (j=1; j<len_t && j<=i; j++) {                if (S[i]!=T[j]) {                    dp[i][j] = dp[i-1][j];                    //cout<<dp[i-1][j]<<endl;                }                else{                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j];                    //dp[i-1][j-1]: use S[i], as S[i]==T[j]                    //dp[i-1][j]  : don't use S[i]                    //cout<<dp[i][j]<<endl;                }            }        }        return dp[len_s-1][len_t-1];    }        int numDistinct(string S, string T) {        len_s = S.length();        len_t = T.length();        return Count(S, T);    }};









聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.