题目:https://leetcode.com/problems/word-break-ii/
思路:
直接用 Recursion超时。取 Word Break 的思路,先 DP 获得 jth 位置可达到的 index,再通过 Recursion 获得所有结果。
Code:
public class Solution {
ArrayList<String> resAL;
HashMap<Integer,ArrayList<Integer>> hm;
public List<String> wordBreak(String s, Set<String> wordDict) {
resAL = new ArrayList<String>();
if(s.length() == 0) return resAL;
hm = new HashMap<Integer,ArrayList<Integer>>();
boolean[] res = new boolean[s.length()+1];
res[0]=true;
for(int i=0; i<s.length();i++){
StringBuilder str = new StringBuilder(s.substring(0,i+1));
for(int j=0;j<=i;j++){
if(res[j] && wordDict.contains(str.toString())){
res[i+1]=true;
ArrayList<Integer> jAL;
if(!hm.containsKey(j)){
jAL = new ArrayList<Integer>();
jAL.add(str.toString().length()+j);
hm.put(j,jAL);
}else{
jAL = hm.get(j);
jAL.add(str.toString().length()+j);
}
}
str.deleteCharAt(0);
}
}
//Print all result
if(res[s.length()]){
recur(s, "", 0);
}
return resAL;
}
public void recur(String s, String resStr, int start){
if(start >= s.length()){
resAL.add(resStr);
return;
}
if(hm.containsKey(start)){
ArrayList<Integer> al = hm.get(start);
for(Integer i: al){
if(start != 0) recur(s, resStr+" "+s.substring(start,i),i);
else recur(s, s.substring(start,i),i);
}
}
}
}
备注: