Distinct Subsequences
Difficulty: Hard · Pattern: 2-D Dynamic Programming · LeetCode #115
Return the number of distinct subsequences of s that equal t.
Examples
text
s = "rabbbit", t = "rabbit" → 3 (choose which of the three b's to drop)
s = "babgbag", t = "bag" → 5Hints
dp[i][j]= the number of ways to formt[:j]froms[:i].- For each character of s: you may skip it, and if it matches
t[j−1], you may also use it.
Approach
text
dp[i][j] = dp[i-1][j] # skip s[i-1]
+ dp[i-1][j-1] if s[i-1]==t[j-1] # use it to match t[j-1]
dp[i][0] = 1 (the empty t can be formed one way)In 1-D, iterate j backwards so dp[j−1] is still the previous row's value. That's O(m·n) time and O(n) space. A quick check: if len(t) > len(s), the answer is 0.
Complexity
Time: O(m·n). Space: O(n).
Python solution
def numDistinct(s, t):
n = len(t)
dp = [1] + [0] * n
for ch in s:
for j in range(n, 0, -1):
if ch == t[j - 1]:
dp[j] += dp[j - 1]
return dp[n]JavaScript solution
function numDistinct(s, t) {
const n = t.length, dp = new Array(n + 1).fill(0);
dp[0] = 1;
for (const ch of s) for (let j = n; j >= 1; j--) if (ch === t[j - 1]) dp[j] += dp[j - 1];
return dp[n];
}