// 算法:DFS
// 递归函数参数使用引用
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
时间: 2024-12-31 03:50:52