Distinct Subsequences
Problem
Given two strings s and t, return the number of distinct subsequences of s that equal t.
s = "rabbbit", t = "rabbit"3def 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]
function numDistinct(s, t) {
const m = s.length, n = t.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = 1;
for (let i = 1; i <= m; i++) {
for (let 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];
}
class Solution {
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];
}
}
int numDistinct(string s, string t) {
int m = s.size(), n = t.size();
vector<vector<long>> dp(m + 1, vector<long>(n + 1, 0));
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 (int)dp[m][n];
}
Explanation
We want to count how many ways the target t hides inside s as a subsequence. The clean way is a 2D DP over prefixes: dp[i][j] is the number of ways the first j characters of t appear in the first i characters of s.
For each cell we always have the option of not using the current character of s, which carries over dp[i-1][j]. If s[i-1] equals t[j-1], we additionally have the option of matching them, which adds dp[i-1][j-1]. So dp[i][j] = dp[i-1][j] + (match ? dp[i-1][j-1] : 0).
The base case is dp[i][0] = 1: an empty target matches any prefix of s in exactly one way (pick nothing).
Example: s = "rabbbit", t = "rabbit". There are three b's and t needs two, so the three ways correspond to dropping each one of the three b's once. The DP lands on 3.
We fill an m × n grid, doing constant work per cell, so the running time is proportional to m · n.