[leetcode刷题系列]Word Ladder II
来源:互联网 发布:淘宝号怎样会被冻结 编辑:程序博客网 时间:2024/06/06 00:19
这题时间卡的还真是严啊- -
先bfs一遍,标记没个单词属于哪一层, 然后从end开始往回走,就好了
string start, end;unordered_map<string, int> lev;void dfs(string now, vector<string> & stk, vector<vector<string> > & ret){ if(now == start){ vector<string> tmp(stk); tmp.push_back(now); reverse(tmp.begin(), tmp.end()); ret.push_back(tmp); return ; } stk.push_back(now); for(int i = 0; i < now.size(); ++ i) for(char c = 'a'; c <= 'z'; ++ c){ string next(now); next[i] = c; if(next == now) continue; if(lev.find(next) != lev.end() && lev[next] == lev[now] - 1){ dfs(next, stk, ret); } } stk.pop_back();}class Solution {public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<string> > ret; if(start == end){ ret.resize(1); ret[0].push_back(start); return ret; } ::start = start; ::end = end; lev.clear(); queue<string> q; lev[start] = 0; q.push(start); while(!q.empty()){ string now = q.front(); q.pop(); if(now == end) continue; for(int i = 0; i < now.size(); ++ i) for(char c = 'a'; c <= 'z'; ++ c){ string next(now); next[i] = c; if(next == end || dict.find(next) != dict.end()) if(lev.find(next) == lev.end()){ lev[next] = lev[now] + 1; q.push(next); } } } vector<string> stk; dfs(end, stk, ret); return ret; }};
- [leetcode刷题系列]Word Ladder II
- [leetcode刷题系列]Word Ladder
- 【leetcode】Word Ladder II
- [LeetCode]Word Ladder II
- [leetcode] Word Ladder II
- LeetCode - Word Ladder II
- Leetcode: Word Ladder II
- leetcode Word Ladder II
- Leetcode Word Ladder II
- LeetCode | Word Ladder II
- leetcode word ladder II
- 【Leetcode】Word Ladder II
- [LeetCode] Word Ladder II
- Word Ladder II -- LeetCode
- Leetcode: Word Ladder II
- leetcode-Word Ladder II
- leetcode-Word Ladder II
- leetcode: Word Ladder II
- 让Android自带的Gallery实现多点缩放,拖动和边界回弹效果,效果流畅
- spinner下拉列表的使用
- hdu 4488 Faulhaber’s Triangle
- wikioi 丘比特的烦恼 (最大权匹配)
- Python批量修改文件名
- [leetcode刷题系列]Word Ladder II
- 学习C++实践者的方法
- CCTexture2D CCSpriteBatchNode CCTextureCache CCSpriteFrameCache 分析
- 博弈论学习小结&HDU 4664#by zh
- JDBC连接数据库字符串
- 成为高效程序员的7个重要习惯
- VLAN聚合(VLAN Aggregation)
- 1039. Course List for Student (25)-PAT
- 第一次使用GitHub