Word Break II
Return every sentence formed by splitting a string into dictionary words.
Open on LeetCode ↗Intuition
Trying every cut generates many dead branches and recomputes sentences for the same suffix. Once a prefix word is selected, every completion depends only on the index immediately after it. Memoize the list of sentences constructible from each starting index. Combining the chosen word with each cached suffix produces all valid sentences without duplicate subproblem work.
A request to return all segmentations combines backtracking for enumeration with DP for repeated suffixes. Memoize complete result lists by starting index rather than only whether a suffix is possible.
Approach
Search sentences from a suffix boundary
Define build(start) as every space-separated sentence that forms s[start:]. At the end of the string, return a list containing the empty sentence so a final word has one valid completion to attach to.
Try only dictionary prefixes
For each possible end position, inspect s[start:end] and continue only if that substring belongs to the word set. This makes each recursive step correspond to one legal word.
Combine words with cached suffix sentences
For every sentence returned from build(end), append either word + ' ' + suffix or just word when the suffix is empty. Cache the completed list for start because many earlier splits may reach it.
Solution
Common pitfalls
Returning no completion at the string end
if start == len(s):
return []if start == len(s):
return ['']The caller needs one neutral completion to emit its final chosen word.
Always appending a space
sentences.append(word + ' ' + suffix)
sentences.append(word if not suffix else word + ' ' + suffix)
The terminal empty suffix would otherwise create trailing whitespace.
Caching only booleans
memo[start] = can_break
memo[start] = sentences
The output requires every actual sentence, not merely feasibility.
Edge cases
Every branch returns an empty list, so the final result is empty.
The empty-suffix base case yields that word without a trailing space.
Memoization constructs that suffix's sentences once and reuses them.