codejump
HardPro challengePythonJavaScriptTypeScript

DP — Distinct Subsequences

AlgorithmsDynamic ProgrammingStrings

solve(s, t) — return the number of distinct subsequences of s that equal
t. A subsequence keeps the relative order of characters but may skip some; two
subsequences are distinct if they use different index sets, even when the text is
the same.

Let ways[j] be the number of ways to form the first j characters of t from
the part of s read so far. Scan s; when a character equals t[j-1], you can
use it to extend every way that formed t[0..j-1). Update j from high to low so
that one character of s is not used twice.

Examples

solve("rabbbit", "rabbit")  → 3
solve("babgbag", "bag")     → 5
solve("aaa", "aa")          → 3
solve("abc", "abcd")        → 0
solve("a", "")              → 1

Sample tests

Test #1Classic example
Input: ["rabbbit","rabbit"]
Output: 3
Test #2Five index sets
Input: ["babgbag","bag"]
Output: 5
Test #3Empty target
Input: ["a",""]
Output: 1