F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[Leetcode] Word Break II

此题和另外word ladder II 有异曲同工之妙,最终路径的搜索都是用图。

这种搜索路径的题目实际上可以总结出一个非常通用的减少递归深度,计算量的方法,是使用一定的预处理措施,
将前期的依赖关系简化为一个图,然后使用图算法来进行路径的计算

 

 1 import java.util.*;
 2 
 3 public class Solution {
 4 
 5     private void DFS(List<List<String>> map,List<String> path,List<String> res,int end){
 6         if(end==-1){
 7             String resone = "";
 8             for(int i=path.size()-1;i>=0;i--){
 9                 if(i==path.size()-1)
10                     resone = path.get(i);
11                 else
12                     resone = resone+" "+path.get(i);
13             }
14             res.add(resone);
15             return;
16         }
17         if(end<-1) return;
18         List<String> words = map.get(end);
19         for(String w: words){
20             path.add(w);
21             DFS(map,path,res,end-w.length());
22             path.remove(path.size()-1);
23         }
24     }
25     public List<String> wordBreak(String s, Set<String> wordDict) {
26         List<String> res = new LinkedList<String>();
27         if(s==null||s.length()==0) return res;
28         List<List<String>> map = new LinkedList<List<String>>();        
29         boolean [] flag = new boolean[s.length()];
30         for(int i=0;i<s.length();i++){
31             List<String> listone = new LinkedList<String>();//以index i结尾的单词的个数
32             for(int j=i;j>=0;j--){
33                 String sub = s.substring(j,i+1);
34                 if(wordDict.contains(sub)&&(j==0||flag[j-1])){
35                     listone.add(sub);
36                     flag[i]=true;
37                 }
38             }
39             map.add(listone);
40         }
41         List<String> path = new LinkedList<String>();
42         DFS(map,path,res,s.length()-1);
43         return res;
44     }
45 }

 

[1] Word Ladder II

[2] http://www.cnblogs.com/deepblueme/p/4733771.html

posted on 2015-08-29 12:09  F_G  阅读(204)  评论(0编辑  收藏  举报