Saturday, February 28, 2015

Distinct Subsequences

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.

--------------------------- thinking ----------------------------------
https://oj.leetcode.com/discuss/19735/a-dp-solution-with-clarification-and-explanation

BUG -> please pay attention to the order of i and j, which represents the index of source string and target string!

Please try to optimize the codes below by using less memory!
---------------------------- codes -------------------------------------
class Solution {
public:
    int numDistinct(string S, string T) {
        int slen = S.size();
        int tlen = T.size();
       
        int dp[tlen+1][slen+1];
        memset(dp, 0, sizeof(dp));
        for (int i = 0; i < slen+1; i++) {
            dp[0][i] = 1;
        }
        for (int j = 1; j < tlen+1; j++) {
            for (int i = 1; i < slen+1; i++) {
                if (S[i-1] == T[j-1]) {
                    //bug here ->i represent the source string!!!! should add dp[j][i-1] instead of dp[j-1][i]
                    dp[j][i] = dp[j-1][i-1] + dp[j][i-1];
                } else {
                    dp[j][i] = dp[j][i-1];
                }
            }
        }
        return dp[tlen][slen];
    }
};

No comments:

Post a Comment