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.

    r a b b i t
  1 0 0 0 0 0 0 
r 1 1 0 0 0 0 0
a 1 1 1 0 0 0 0
b 1 1 1 1 0 0 0
b 1 1 1 2 1 0 0
b 1 1 1 3 3 0 0
i 1 1 1 3 3 3 0
t 1 1 1 3 3 3 3

From the table we can see results[i][j] (from S->T) is at least equal to results[i-1][j]

public int numDistinct(String S, String T) {
        if (S==null||T==null) {
            return 0;
        }

        int[][] results = new int[S.length()+1][T.length()+1];

        //empty string is substring of any string
        for (int i=0; i<results.length; i++) {
            results[i][0] = 1;
        }

        for (int i=1; i<results.length; i++) {
            for (int j=1; j<results[i].length; j++) {
                results[i][j] = results[i-1][j];
                if (S.charAt(i-1) == T.charAt(j-1)) {
                    results[i][j] += results[i-1][j-1];
                }
            }
        }

        return results[S.length()][T.length()];
    }