LeetCode Word Ladder II
2015-06-14 01:18
323 查看
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.
TLE
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.
class Solution { private: vector<vector<string>> res; public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { res.clear(); unordered_map<string, vector<string> > paths; queue<string> que; que.push(start); dict.insert(end); vector<string> del; del.push_back(start); while (!que.empty()) { int size = que.size(); for (string& s : del) { dict.erase(s); } del.clear(); for (int i=0; i<size; i++) { string str = que.front(); string orig = str; que.pop(); if (str == end) { continue; } for (char& ch : str) { for (char c = 'a'; c <= 'z'; c++) { if (ch == c) { continue; } char t = ch; ch = c; if (dict.count(str) > 0) { del.push_back(str); que.push(str); if (paths.count(str) == 0) { paths.insert(make_pair(str, vector<string>())); } paths[str].push_back(orig); } ch = t; } } } } vector<string> path; path.push_back(end); build_path(paths, path, end); return res; } void build_path(unordered_map<string, vector<string> > paths, vector<string>& path, string prev) { if (paths.count(prev) == 0) { if (path.size() < 2) return; reverse(path.begin(), path.end()); res.push_back(path); return; } vector<string>& strs = paths[prev]; for (string& s : strs) { path.push_back(s); build_path(paths, path, s); path.pop_back(); } } };
TLE
相关文章推荐
- python opencv face detection
- 算素因子种类数个个数的题目
- 【设计模式】【单例类】
- Java8 Stream forEach()函数的效率问题
- Android屏幕适配
- memset对数组的初始化
- memset对数组的初始化
- ListView添加header后需要解决的问题
- 私服 Nexus 的配置
- 令人感动的歌词
- IPMI总结
- boost::bind的疑问
- ANSI和UNICODE字符的相互转化
- 欢迎使用CSDN-markdown编辑器
- WWDC2015 结束.新一波更新以及bug即将来袭.
- 终于从百度空间手动搬家过来了
- text-transform
- 布尔表达式的判断设置
- 双向链表(3) - 反转双向链表
- leetcode 30 -- Substring with Concatenation of All Words