Problem
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Explanation
-
When the question asks to return all different situation, we can usually use recursion to solve it.
-
First, we can think of how we solve it in a manual way. From the above example 1, we will find if any string from the
wordDict
can be the beginning of thes
. We can check it using the length of string and ifs[0:stringFromArr.length] == stringFromArr
, then thestringFromArr
can be the beginning ofs
. In example1, we find out cat and cats both can be the beginning ofs
. If we choose cat, thens
becomes “sanddog”. We again find the beginning string from thewordDict
, then we find out “sand” also from the beginning of the string, thens
becomes “dog”, and it also inside thewordDict
, this mean we find out result string. -
This method can use recursion to solve it because when
s
is changed, the way to solve is the same. This is a brute force way, and we are doing repeated work. For example, whens
becomes “sanddog”, we know it can split to “sand” and “dog”. If we face “sanddog” again, then we don’t want to recursive to solve again, we want to save this result. Because we have to saves
and the its splitted strings at the same time, then we can use ahashmap<String, List<String>>
. -
In the recursion function, the base case will be if the map has key, then we just return the value. If
s
is empty, then we return an empty string inside an array because between each string, there’s a space, but at the end, there’s no space. -
In summary, we iterate the
wordDict
array, and check if a stringword
can be the beginning ofs
, then we pass its following string to the recursive function and save the result array asrem
. Then, we iterate each result string inrem
and concatnateword
to form one string, and push this string to the result array.
Solution
1 |
|