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.
For example, given
s =”catsanddog”,
dict =[“cat”, “cats”, “and”, “sand”, “dog”].
A solution is[“cats and dog”, “cat sand dog”].
import java.util.*;
public class Solution {
HashMap<String,ArrayList<String>> map=new HashMap<String,ArrayList<String>>();
public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> list=new ArrayList<String>();
if(s==null||s.length()==0){
return list;
}
if(map.containsKey(s)){
return map.get(s);
}
if(dict.contains(s)){
list.add(s);
}
for(int i=1;i<s.length();i++){
String str=s.substring(i);
if(dict.contains(str)){
List<String> a=wordBreak(s.substring(0,i),dict);
for(int j=0; j<a.size();j++){
list.add(a.get(j)+" "+str);
}
}
}
map.put(s,list);
return list;
}
}