Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S.

  • Time: O(n * m)
  • Space: O(n * m)
public int numDistinct(String s, String t) {
    int m = t.length(), n = s.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 0; i <= n; i++) {
        dp[0][i] = 1;
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (s.charAt(j) == t.charAt(i)) {
                dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j];
            } else {
                dp[i + 1][j + 1] = dp[i + 1][j];
            }
        }
    }
    return dp[m][n];
}

results matching ""

    No results matching ""