Problem
Given a string s
and a dictionary of strings wordDict
, add spaces in s
to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
We have already seen part 1 of the problem - Word Break 1 - Check if word is breakable. Instead of using a boolean array to track the matched positions, we need to track the actual matched words.
Method 1 - Backtracking
We have seen Word Break 1 - Check if word is breakable#Method 1 - Brute force - Generate all substrings. We will use solution similar to Subsets.
Video Explanation
Here is the video explanation:
Code
|
|
Complexity
- ⏰ Time complexity:
O(2^n)
- 🧺 Space complexity:
O(n + m)
- where n is the length of string s, and m is number of words in dict
Method 2 - Dynamic Programming
#TODO use DP solution used in Word Break 1 - Check if word is breakable.
Method 3 - Using Trie
#TODO work on this solution later