Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
Example
Example 1:
Input:"lintcode",["de","ding","co","code","lint"]
Output:["lint code", "lint co de"]
Explanation:
insert a space is "lint code",insert two spaces is "lint co de".
Example 2:
Input:"a",[]
Output:[]
Explanation:dict is null.
思路:用dfs 搜索所有的解空间,用memory cache加速;用hashmap去记录一下中间计算的结果,去掉重复计算;
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<String>(wordDict);
HashMap<String, List<String>> hashmap = new HashMap<>();
return dfs(s, set, hashmap);
}
// s 分成两半
// prefix + 子问题 -> list of string;
// prefix + " " + suffix;
public List<String> dfs(String s, HashSet<String> set, HashMap<String, List<String>> hashmap) {
if(hashmap.containsKey(s)) {
return hashmap.get(s);
}
List<String> list = new ArrayList<>();
if(set.contains(s)) {
list.add(s);
}
for(int i = 1; i < s.length(); i++) {
String prefix = s.substring(0, i);
if(set.contains(prefix)) {
for(String suffix: dfs(s.substring(i), set, hashmap)) {
list.add(prefix + " " + suffix);
}
}
}
hashmap.put(s, list);
return list;
}
}