Leetcode Distinct Subsequences

OpenSoucre發表於2014-07-03

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相等的個數,如果熟悉《演算法導論》的話,可以想到動態規劃那一節關於由一個字串通過增刪變成另一個字串解法

本題利用動態規劃求解

設決策變數為path[i][j],表示S[1..i]的前i個字元通過刪除字元變成T[1..j]的個數

那麼狀態轉移方程為

                       path[i-1][j-1]  (S[i] == T[j])

path[i][j] = path[i-1][j](刪除S的第i個字元)+                  (不刪除字元)

                          0       (S[i] != T[j] )

 

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

 

 

相關文章