码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Word Ladder II 之一

时间:2014-09-14 11:18:47      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   strong   

// 算法:DFS

// 递归函数参数使用引用

// Time Limit Exceeded

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector< vector<string> > findLadders( string start, string end, unordered_set<string > &dict) {
 4            
 5           vector< vector< string>  >  ret;
 6           vector<string> path;
 7                   if( start == end ) {
 8             path.push_back(start);
 9             ret.push_back(path);
10             return ret;
11                   } 
12           else  if(dict.empty()){
13             return ret;
14            }
15            unordered_set<string> vis;
16            path.push_back(start);
17            vis.insert(start);
18            dfs(start,end,dict,path, vis, ret);
19 
20            return ret;
21      }
22 
23 private:
24 // 修改了函数参数
25      void  dfs( string start, string end, const unordered_set<string>& dict, 
26                 vector<string>&  path, unordered_set<string>&  vis,vector<vector<string>  >&  ret )
27      {
28            size_t len = start.size();      
29            for( int i = 0;i < len ;i++)
30            {
31                 for( char j = a ; j <= z ;j++)
32                 {
33                     
34                     if( j == start[i]){
35                         continue;
36                     }
37                     string  tmp = start;
38                     tmp[i] = j ;
39                     
40                     if( tmp == end) {
41                         path.push_back(end);
42                         if(  ret.empty()  || ret[0].size() == path.size() ){
43                             ret.push_back(path);
44                         }
45                         else if( ret[0].size() > path.size() )    {
46                             ret.clear();
47                             ret.push_back(path);                        
48                         }
49                         path.pop_back();
50             
51                         return;
52                 
53                     }
54                 
55                     if (  dict.count(tmp) == 0 || vis.count(tmp) != 0 ) {                        
56                         continue;
57                     }
58                     
59                     path.push_back(tmp);
60                     vis.insert(tmp);
61 
62                     dfs(tmp,end,dict,path,vis,ret);
63 
64                     path.pop_back();
65                     vis.erase(tmp);
66 
67                 }
68 
69            }
70      }
71 };
72                
View Code

 

[LeetCode] Word Ladder II 之一

标签:style   blog   http   color   io   os   使用   ar   strong   

原文地址:http://www.cnblogs.com/wmzhang/p/3970759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!