leetcode_question_115 Distinct Subsequences

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 .
Recurse: Judge Small: Accepted! Judge Large: Time Limit Exceeded
int numDistinct(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int slen = S.length();
        int tlen = T.length();
        if(slen <= tlen){
            if(S == T) return 1;
            else return 0;
        }
        
        if(S[slen-1] != T[tlen-1]) return numDistinct(S.substr(0,slen-1), T);
        else
            return numDistinct(S.substr(0,slen-1), T) + numDistinct(S.substr(0,slen-1), T.substr(0,tlen-1));
    }

dp: Judge Small: Accepted! Judge Large: Accepted!
int numDistinct(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int col = S.length() + 1;
        int row = T.length() + 1;
        int** dp = new int*[row];
        for(int i = 0; i < row; ++i)
            dp[i] = new int[col];
        
        for(int i = 0; i < row; ++i)
            dp[i][0] = 0;
        for(int j = 0; j < col; ++j)
            dp[0][j] = 1;
        
        for(int i = 1; i < row; ++i)
            for(int j = 1; j < col; ++j)
                if(T[i-1] == S[j-1]) dp[i][j] = dp[i-1][j-1] + dp[i][j-1];
                else dp[i][j] = dp[i][j-1];
                
        int tmp = dp[row-1][col-1];
        
        for(int i = 0; i < row; ++i)
            delete[] dp[i];
        delete[] dp;
        
        return tmp;
    }

좋은 웹페이지 즐겨찾기