[LeetCode] Word Ladder II 之一
2014-09-14 10:47
387 查看
// 算法:DFS
// 递归函数参数使用引用
// Time Limit Exceeded
View Code
// 递归函数参数使用引用
// Time Limit Exceeded
class Solution { public: vector< vector<string> > findLadders( string start, string end, unordered_set<string > &dict) { vector< vector< string> > ret; vector<string> path; if( start == end ) { path.push_back(start); ret.push_back(path); return ret; } else if(dict.empty()){ return ret; } unordered_set<string> vis; path.push_back(start); vis.insert(start); dfs(start,end,dict,path, vis, ret); return ret; } private: // 修改了函数参数 void dfs( string start, string end, const unordered_set<string>& dict, vector<string>& path, unordered_set<string>& vis,vector<vector<string> >& ret ) { size_t len = start.size(); for( int i = 0;i < len ;i++) { for( char j = 'a' ; j <= 'z' ;j++) { if( j == start[i]){ continue; } string tmp = start; tmp[i] = j ; if( tmp == end) { path.push_back(end); if( ret.empty() || ret[0].size() == path.size() ){ ret.push_back(path); } else if( ret[0].size() > path.size() ) { ret.clear(); ret.push_back(path); } path.pop_back(); return; } if ( dict.count(tmp) == 0 || vis.count(tmp) != 0 ) { continue; } path.push_back(tmp); vis.insert(tmp); dfs(tmp,end,dict,path,vis,ret); path.pop_back(); vis.erase(tmp); } } } };
View Code
相关文章推荐
- LeetCode: Word Ladder II
- LeetCode 126. Word Ladder II
- 【LeetCode】126. Word Ladder II【H】
- Leetcode_word-ladder-ii
- leetcode — word-ladder-ii
- LeetCode: Word Ladder II [127]
- LeetCode: Word Ladder II
- LeetCode 126 Word Ladder II
- [LeetCode] Word Ladder II 词语阶梯之二
- Leetcode 127. Word Ladder I & 126. Word Ladder II
- Leetcode 126 word ladder II
- [LeetCode] Word Ladder II
- Word Ladder II -- LeetCode
- LeetCode | Word Ladder II(单词梯II)
- leetcode word ladder II
- [leetcode 126] Word Ladder II
- Leetcode: Word Ladder II
- leetcode——Word Ladder II
- [leetcode] Word Ladder II
- 【Leetcode】Word Ladder II (Backtracking)