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"]
.
找到所有拆分组合
DFS遗憾的又超时了,要保存下中间结果,DP用map找到有解后续节点list,然后DFS输出所有解
public class Solution {
public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> ret = new ArrayList<String>();
Map<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();
buildPos(s, dict, map);
if(map.get(0)==null)
return ret;
print(s,map,ret,"",0);
return ret;
}
private void print(String s, Map<Integer, List<Integer>> map,ArrayList<String> ret,String tmp,int pos) {
if(pos==s.length()){
ret.add(tmp.substring(0, tmp.length()-1));
return;
}
List<Integer> list = map.get(pos);
for(int i : list){
print(s, map, ret, tmp+s.substring(pos,i)+" ",i);
}
}
private void buildPos(String s, Set<String> dict,Map<Integer,List<Integer>> map){
List<Integer> list = new ArrayList<Integer>();
for(int i=s.length()-1;i>=0;i--){
for(int j=list.size()-1;j>=0;j--){
if(dict.contains(s.substring(i, list.get(j)))){
List<Integer> tmp = map.get(i);
if(tmp==null){
tmp=new ArrayList<Integer>();
map.put(i,tmp);
}
tmp.add(list.get(j));
}
}
if(dict.contains(s.substring(i))){
List<Integer> tmp = map.get(i);
if(tmp==null){
tmp=new ArrayList<Integer>();
map.put(i,tmp);
}
tmp.add(s.length());
}
List<Integer> tmp = map.get(i);
if(tmp!=null)
list.add(i);
}
}
}