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超时
public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
LinkedList<String> res=new LinkedList<String>();
LinkedList<String> path=new LinkedList<String>();
if(s==null || dict==null || dict.size()==0) return res;
int n=s.length();
boolean []f=new boolean[n+1];
boolean [][]prev=new boolean[n+1][n];
f[0]=true;
//dp
for(int i=1;i<=n;i++){
for(int j=i-1;j>=0;j--){
if( f[j] && dict.contains( s.substring(j,i) ) ){
f[i]=true;
prev[i][j]=true;
}
}
}
getPath(s.length(),s,prev,res,path);
return res;
}
//dfs
public void getPath(int curr,String s, boolean [][]prev,LinkedList<String> res,LinkedList<String> path){
if(curr==0){
StringBuilder sb=new StringBuilder();
for(String ss : path){
sb.append(ss);
sb.append(" ");
}
res.add(sb.toString().trim());
}
for(int i=0;i<curr;i++){
if(prev[curr][i]){
path.addFirst(s.substring(i,curr));
getPath(i,s,prev,res,path);
path.pollFirst();
}
}
}
}