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).

Notes:

  1. Double sequence DP
  2. State: f[i][j] the subsequence number of string A[0..i] contains string B[0..j]
  3. Function:
    1. f[i][j] = f[i-1][j] when A[i] != B[j]
    2. f[i][j] = f[i-1][j] + f[i-1][j] when A[i] == B[j]
  4. Initialize: f[i][0] = 1, f[0][i] = 0
  5. Answer: f[m][n]
    public int numDistinct(String s, String t) {
        if (s == null || t == null) {
            return 0;
        }

        int m = s.length();
        int n = t.length();

        // state
        int[][] f = new int[m+1][n+1];

        // initialize
        for (int i = 0; i <= m; ++i) {
            f[i][0] = 1;
        }

        // for (int j = 1; j <= n; ++j) {
        //     f[0][j] = 0;
        // }

        // function
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (s.charAt(i-1) == t.charAt(j-1)) {
                    f[i][j] = f[i-1][j] + f[i-1][j-1];
                } else {
                    f[i][j] = f[i-1][j];
                }
            }
        }

        // answer
        return f[m][n];
    }

results matching ""

    No results matching ""