Word Ladder II
2015-07-08 20:54
288 查看
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from
start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start =
end =
dict =
Return
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
Solution:
start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start =
"hit"
end =
"cog"
dict =
["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
Solution:
class Solution { public: vector<vector<string>> res; void dfsPath(unordered_map<string, unordered_set<string>> &path, vector<string> &temp, const string &key) { if(path[key].size() == 0) { temp.push_back(key); vector<string> tempPath = temp; reverse(tempPath.begin(), tempPath.end()); res.push_back(tempPath); temp.pop_back(); return ; } temp.push_back(key); for(unordered_set<string>::iterator iter = path[key].begin(); iter != path[key].end(); ++iter) { dfsPath(path, temp, *iter); } temp.pop_back(); } vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { res.clear(); unordered_set<string> current; unordered_set<string> next; unordered_map<string, unordered_set<string>> path; if(dict.count(start) > 0) dict.erase(start); current.insert(start); while(current.count(end) == 0 && !dict.empty()) { for(unordered_set<string>::iterator iter = current.begin(); iter != current.end(); ++iter) { string str = *iter; for(int i = 0; i < str.length(); ++i) { for(char c = 'a'; c <= 'z'; ++c) { string tmp = str; if(tmp[i] == c) continue; tmp[i] = c; if(dict.count(tmp) > 0) { path[tmp].insert(str); next.insert(tmp); } } } } if(next.empty()) break; for(unordered_set<string>::iterator iter = next.begin(); iter != next.end(); ++iter) { dict.erase(*iter); } current = next; next.clear(); } vector<string> temp; if(current.count(end) > 0) dfsPath(path, temp, end); return res; } };
相关文章推荐
- 黑马程序员————C语言总结(1)
- 599 奋斗的小蜗牛
- unity调用Android通过编译 java jar包出现问题解决和简单支付流程
- 最佳vim技巧
- 5类双绞线的线序
- 进程上下文 中断上下文
- Linux中的权限以及访问控制
- Linux中的权限以及访问控制
- [leetcode-54]Spiral Matrix(C语言)
- 游标
- Intent
- 【剑指offer】题目38 数字在排序数组中出现的次数
- 如果数组长度n为奇数,则将数组中最大的元素放到 output[] 数组最中间的位置
- HAproxy+keepalived+mysql高可用性Linux系统集群
- Unity 脚步 事件函数 的执行顺序
- Objective-C中的Block
- ACM--搬寝室
- freemarker XMLGregorianCalendar 转日期
- 2015湖南省队集训DAY6——B题(BZOJ4179)
- 名字的漂亮度