Overview
This is a string matching problem where we can delete characters from the source string to match the target string, counting all distinct ways to do so.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given two strings S and T, return the number of distinct subsequences of S which equal T.
This is a string matching problem where we can delete characters from the source string to match the target string, counting all distinct ways to do so.
Let `dp[i][j]` be the number of ways to form the prefix of `T` of length `j` using the prefix of `S` of length `i`.
If `S[i] == T[j]`, we can either use `S[i]` to match `T[j]` (`dp[i-1][j-1]`), OR we can ignore `S[i]` and rely on earlier characters (`dp[i-1][j]`).
If they don't match, we cannot use `S[i]`, so we MUST ignore it: `dp[i][j] = dp[i-1][j]`.
| S \ T | "" | r | a | b | b | i | t |
|---|---|---|---|---|---|---|---|
| "" | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| r | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| a | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| b | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| b | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| b | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| i | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| t | 1 | 0 | 0 | 0 | 0 | 0 | 0 |