Link: https://leetcode.com/problems/word-break-ii/
Solution:
DSA: DFS, subarray, set, grow, shrink
Intuition
The key to understanding this problem is realizing that we can shrink s
, and grow the current sentence.
For example:
curr_s | s
---------------------
'' catsanddog
cats anddog
cats and dog
cats and dog ''
So we can construct our recursion following the grow/shrink pattern. And when len(s) == 0
, we have taken everything we can from it, which means curr_s
is a valid sentence!
In a recursive function, we would check all substrings of s starting at 0 if its a word in word_dict, if it is, then we shrink s
and grow curr_s
, and recursively call on those parameters.
Implementation
Visual
Review 1
We can also use back tracking for this problem for a minor boost in memory efficiency.
Implementation (back tracking)