public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
return helper(s, wordDict, new HashMap<String, List<String>>());
}
public List<String> helper(String s, Set<String> wordDict, HashMap<String, List<String>> map) {
if (map.containsKey(s)) {
return map.get(s);
}
List<String> result = new ArrayList<String>();
if (s.length() == 0) {
return result;
}
for (String str : wordDict) {
if (str.length() > s.length()) {
continue;
}
if (str.equals(s.substring(0, str.length()))) {
if (str.equals(s)) {
result.add(str);
}
List<String> list = helper(s.substring(str.length()), wordDict, map);
for (String ss : list) {
result.add(str + " " + ss);
}
}
}
map.put(s, result);
return result;
}
}