2014年10月22日星期三

[Leetcode] 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.
DP problem. We use dp[i][j] to indicate the number of T[0...j] in S[0...i]. Then we could have following statements:

  1. if S[i] == T[j], we could match T[j] to S[i] to get some new staffs and plus the prior ones thus we have dp[i][j] = dp[i-1][j-1] + dp[i-1][j].
  2. if S[i] != T[j], we could only thous prior ones which give dp[i][j] = dp[i-1][j].
Pay attention to the initial states.

    public int numDistinct(String S, String T) {
        int m = S.length();
        int n = T.length();
        int[][] dp = new int[m+1][n+1];
        
        for(int i = 0; i <= m; i++) {
            for(int j = 0; j <= n; j++) {
                if(i == 0 && j == 0)
                    dp[i][j] = 1;
                else if(i == 0)
                    dp[i][j] = 0;
                else if(j == 0) 
                    dp[i][j] = dp[i-1][j];
                else {
                    if(S.charAt(i-1) == T.charAt(j-1))
                        dp[i][j] = dp[i-1][j] + dp[i-1][j-1];
                    else
                        dp[i][j] = dp[i-1][j];
                }
            }
        }
        
        return dp[m][n];
    }

没有评论:

发表评论