Word Break II

Given anon-emptystring_s_and a dictionary_wordDict_containing a list ofnon-emptywords, 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:
Input:
s = "
catsanddog
"
wordDict =
["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation:
Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]

Solution

JAVA solution based on memorized DFS

public List<String> wordBreak(String s, Set<String> wordDict) {
return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
}
// DFS function returns an array including all substrings derived from s.
List<String> DFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>>map) {
if (map.containsKey(s))
return map.get(s);
LinkedList<String>res = new LinkedList<String>();
if (s.length() == 0) {
res.add("");
return res;
}
for (String word : wordDict) {
if (s.startsWith(word)) {
List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
for (String sub : sublist)
res.add(word + (sub.isEmpty() ? "" : " ") + sub);
}
}
map.put(s, res);
return res;
}
Modified version:
public class Solution {
private HashMap<String,List<String>> map = new HashMap<String, List<String>>();
public List<String> wordBreak(String s, List<String> wordDict) {
List<String> res = new ArrayList<String>();
if(s == null || s.length() == 0) {
return res;
}
if(map.containsKey(s)) {
return map.get(s);
}
if(wordDict.contains(s)) {
res.add(s);
}
for(int i = 1 ; i < s.length() ; i++) {
String t = s.substring(i);
if(wordDict.contains(t)) {
List<String> temp = wordBreak(s.substring(0 , i) , wordDict);
if(temp.size() != 0) {
for(int j = 0 ; j < temp.size() ; j++) {
res.add(temp.get(j) + " " + t);
}
}
}
}
map.put(s , res);
return res;
}
}