This problem is quite similar to Interleaving String, but the solution is almost the same as Regular Expression Matching: we build top-down solution by backtracking, then build bottom-up solution of dp.
Intro problem
Let’s discuss a simplified problem: How to check if t is a subsequence of s? Using a greddy strategy, this would be quite straight forward:
Iterate through
s, matchtin a greddy manner.
- If
thas been iterated over, we find a match. - If
shas been iterated over, we need to iterate overtas well, or there’s no match, search over. - If not 1 or 2, we need to continue searching, skip the characters in
s[0]which don’t matcht[0]
|
|
Backtracking
Borrowing the idea from last section, we need to count all of the possible match, so we can’t stop when we find a character matches, we need to skip this match and explore if there’re other possibilities to achieve a match.
We define search(i, j) to be the distinct subsequences for s[i:] and t[j:], despite that we search for the current match, we still goes for further possibilities in s
|
|
Note:
- We can easily optimize time complexity by using a cache to avoid duplicate calculation. See Optimize Recursion.
Dynamic Programming
WIP