Algo-Sim › Dynamic Programming

Distinct Subsequences

Hard · Dynamic Programming · step through it in Java, Python and C++ on your own input

Count the ways t appears as a subsequence of s. Each matching letter can be used or skipped: dp adds the diagonal to the cell above.

Problem

Given strings s and t, return the number of distinct subsequences of s that equal t: the number of different sets of positions in s whose letters, read in order, spell t.

Constraints

Edge cases to test

Follow-up questions

How do you use one row?
Loop over t from right to left so each update uses the previous row’s value: O(m·n) time, O(n) space.
Can the counts overflow?
Yes, intermediate values can exceed 32 bits; use 64-bit or a modulus if asked.

Solution

Java

public int numDistinct(String s, String t) {
    int m = s.length(), 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];
            if (s.charAt(i - 1) == t.charAt(j - 1)) dp[i][j] += dp[i - 1][j - 1];
        }
    }
    return dp[m][n];
}

Python

def num_distinct(s, t):
    m, n = len(s), len(t)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = 1
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            dp[i][j] = dp[i - 1][j]
            if s[i - 1] == t[j - 1]:
                dp[i][j] += dp[i - 1][j - 1]
    return dp[m][n]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int numDistinct(string &s, string &t) {
        int m = int(s.size()), n = int(t.size());
        vector<vector<int>> dp = vector<vector<int>>(m + 1, vector<int>(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];
                if (s[i - 1] == t[j - 1])
                    dp[i][j] += dp[i - 1][j - 1];
            }
        }
        return dp[m][n];
    }
};

More Dynamic Programming problems