Word Break II leetcode java

題目app

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. ui

Return all such possible sentences. spa

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"]. .net

A solution is ["cats and dog", "cat sand dog"]. code

 

題解blog

這道題不單單是看是否是wordbreak,還須要在此基礎上把全部word break的結果保存。
leetcode

爲了把全部可能性都保存,那麼就使用DFS方法來解決。DFS主要就是跳的層次不容易看出,我下面就以字符串leetcode字典le l et eet code做爲例子畫了一張圖,大概講解了如何遞迴和返回,這樣更加有助於理解。
字符串


 

代碼以下:string

 

 1      public  boolean wordBreakcheck(String s, Set<String> dict) {
 2          if(s== null || s.length()==0)
 3              return  true;
 4          boolean[] res =  new  boolean[s.length()+1];
 5         res[0] =  true;
 6          for( int i=0;i<s.length();i++){
 7             StringBuilder str =  new StringBuilder(s.substring(0,i+1));
 8              for( int j=0;j<=i;j++){
 9                  if(res[j] && dict.contains(str.toString())){
10                     res[i+1] =  true;
11                      break;
12                 }
13                 str.deleteCharAt(0);
14             }
15         }
16          return res[s.length()];
17     }
18     
19      public ArrayList<String> wordBreak(String s, Set<String> dict) {  
20         ArrayList<String> res =  new ArrayList<String>();  
21          if(s== null || s.length()==0)  
22              return res;
23          if(wordBreakcheck(s,dict))
24             helper(s,dict,0,"",res);  
25          return res;  
26     }  
27      private  void helper(String s, Set<String> dict,  int start, String item, ArrayList<String> res){  
28          if(start>=s.length()){  
29             res.add(item);  
30              return;  
31         }
32         
33         StringBuilder str =  new StringBuilder();  
34          for( int i=start;i<s.length();i++){  
35             str.append(s.charAt(i));  
36              if(dict.contains(str.toString())){  
37                 String newItem =  new String();  
38                  if(item.length()>0)
39                     newItem = item + " " + str.toString();
40                  else
41                     newItem = str.toString();
42                 helper(s,dict,i+1,newItem,res);  
43             }  
44         }  
45     }  

 Reference: http://blog.csdn.net/linhuanmars/article/details/22452163
it

相關文章
相關標籤/搜索