115. Distinct Subsequences - jiejackyzhang/leetcode-note GitHub Wiki
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.
解题思路为Dynamic Programming。
##Approach 1: space O(mn) 令dp[i][j]表示number of distinct subsequences of s[0..i-1] and t[0..j-1]。 则:
dp[i][j] = dp[i-1][j] + (dp[i-1][j-1] if s[i-1] == t[j-1] else 0)
base cases为
dp[i][0] = 1
public class Solution {
    public int numDistinct(String s, String t) {
        if(s == null || t == null) return 0;
        int m = s.length();
        int n = t.length();
        int[][] dp = new int[m+1][n+1];
        for(int i = 0; i <= m; i++) dp[i][0] = 1;
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                dp[i][j] = dp[i-1][j] + (s.charAt(i-1) == t.charAt(j-1) ? dp[i-1][j-1] : 0);
            }
        }
        return dp[m][n];
    }
}
##Approach 2: space O(n) 可以将上面方法的table缩减为array。
由于dp[i][j]只基于dp[i-1][j]和dp[i-1][j-1],因此可以只用dp[0..n]一维数组实现。 由于需要dp[i-1][j-1],因此我们update dp的时候采用倒序,这样在计算dp[j]时用到的dp[j-1]表示dp[i-1][j-1]。
dp[0] = 1
dp[j] = dp[j] + (dp[j-1] if s[i-1] == t[j-1] else 0)
public class Solution {
    public int numDistinct(String s, String t) {
        if(s == null || t == null) return 0;
        int m = s.length();
        int n = t.length();
        int[] dp = new int[n+1];
        dp[0] = 1;
        for(int i = 1; i <= m; i++) {
            for(int j = n; j >= 1; j--) {
                if(s.charAt(i-1) == t.charAt(j-1)) dp[j] += dp[j-1];
            }
        }
        return dp[n];
    }
}