#115

Distinct Subsequences

Hard 2D DP counting

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count how many distinct ways t appears as a subsequence of s.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: in how many ways does t appear as a subsequence of s?

Why this works: dp[j] = ways to build t's first j letters. A matching letter of s can extend dp[j-1] (loop j downward).

Example: s "rabbbit", t "rabbit"

choose which 2 of the 3 b's → 3 ways

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Looping j upwards in the 1D version, which reuses the same character of s twice.

Solve on LeetCode ↗
Complexity
  • Time: O(n·m).
  • Space: O(m).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon