[Leetcode Week5]Word Ladder II
Word Ladder II 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/word-ladder-ii/description/
Description
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
- Return an empty list if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Solution
class Solution {
private:
map<string, int> isVisited;
map<string, vector<string>> preVertex;
public:
bool canTrans(string a, string b) {
int count = 0;
for (int i = 0; i < a.length(); i++)
if (a[i] != b[i]) {
if (count == 0)
count++;
else
return false;
}
return count == 1;
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
vector<vector<string>> resultLists;
vector<string> adjacentWordOfEnd;
if (wordList.size() == 0)
return resultLists;
bool endWordExist = false;
for (auto& w: wordList)
if (w == endWord) {
endWordExist = true;
break;
}
if (!endWordExist)
return resultLists;
isVisited[beginWord] = 0;
queue<string> vq;
vq.push(beginWord);
string qfront;
bool flag = false;
while (!vq.empty()) {
qfront = vq.front();
vq.pop();
if (qfront == endWord)
break;
if (canTrans(qfront, endWord)) {
adjacentWordOfEnd.push_back(qfront);
flag = true;
continue;
}
if (flag)
continue;
int curLevel = isVisited[qfront];
for (auto& w: wordList) {
if (canTrans(qfront, w)) {
if (isVisited.count(w) == 0) {
isVisited[w] = curLevel + 1;
vq.push(w);
preVertex[w].push_back(qfront);
} else if (isVisited[w] == 1 + curLevel) {
preVertex[w].push_back(qfront);
}
}
}
}
if (adjacentWordOfEnd.empty())
return resultLists;
queue< stack<string> > pathQueue;
for (auto& w: adjacentWordOfEnd) {
stack<string> path;
path.push(endWord);
path.push(w);
pathQueue.push(path);
}
while (!pathQueue.empty()) {
stack<string> curPath(pathQueue.front());
pathQueue.pop();
string curVertex = curPath.top();
if (curVertex == beginWord) {
insertPath(resultLists, curPath);
} else if (preVertex[curVertex].size() == 1 && preVertex[curVertex].back() == beginWord) {
curPath.push(beginWord);
insertPath(resultLists, curPath);
} else {
for (int i = 1; i < preVertex[curVertex].size(); i++) {
stack<string> newPath(curPath);
newPath.push(preVertex[curVertex][i]);
pathQueue.push(newPath);
}
curPath.push(preVertex[curVertex][0]);
pathQueue.push(curPath);
}
}
return resultLists;
}
void insertPath(vector<vector<string>>& resultLists, stack<string>& reversePath) {
vector<string> path;
while (!reversePath.empty()) {
path.push_back(reversePath.top());
reversePath.pop();
}
resultLists.push_back(path);
}
};
解题描述
这道题是在leetcode上AC的第一道hard的题,花了一天。一开始想到的还是BFS,在Word Ladder的基础上,多记录下完整的路径。但是实际并没有这么简单。这道题要多考虑相同长度的所有路径的情况。所以我起初想到的解决的办法就是通过记录BFS树中所求路径上每一个点的父节点,然后通过获取endWord的所有父节点来向上回溯直到达到beginWord。但是这里我想少了一点,就是其实路径中间的节点也可以和endWord一样拥有多个父节点。解决了这个问题之后,没有过的测例表明,对于endWord同层节点的排除还没有做。所以就另外加了一个flag来标记以排除与endWord同层的点,这才最终AC。
[Leetcode Week5]Word Ladder II的更多相关文章
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- Java for LeetCode 126 Word Ladder II 【HARD】
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- [LeetCode] 126. Word Ladder II 词语阶梯 II
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- LeetCode 126. Word Ladder II 单词接龙 II(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transfo ...
- [Leetcode Week5]Word Ladder
Word Ladder题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder/description/ Description Give ...
- [LeetCode] 126. Word Ladder II 词语阶梯之二
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
- [Leetcode][JAVA] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- [LeetCode#128]Word Ladder II
Problem: Given two words (start and end), and a dictionary, find all shortest transformation sequenc ...
- leetcode 126. Word Ladder II ----- java
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformat ...
随机推荐
- 国际电话区号SQL
CREATE TABLE `phone_prefix` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `country` varchar(30) N ...
- python接口测试(三)——Excell文件读取进行参数化
python进行http请求时,需要对参数进行参数化,此时就可以运用Excel进行,具体如下: 1.梳理出请求中那些参数需要参数化,然后新建一个Excel,如图: 2.读取Excel中的内容,在读取前 ...
- 梳理 Opengl ES 3.0 (三)顶点坐标变换
先来个宏观上的理解: 其实这块逻辑是个标准流程,而且其他地方介绍的也很多了,这里简单提下. 坐标转换,其实是不同坐标系之间的变换,一个渲染顶点,要想让它呈现在屏幕上的某个位置,是需要让这个顶点经过一个 ...
- LeetCode - 1. Two Sum(8ms)
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- LSTM调参经验
0.开始训练之前先要做些什么? 在开始调参之前,需要确定方向,所谓方向就是确定了之后,在调参过程中不再更改 1.根据任务需求,结合数据,确定网络结构. 例如对于RNN而言,你的数据是变长还是非变长:输 ...
- POJ 2161 Chandelier(动态规划)
Description Lamps-O-Matic company assembles very large chandeliers. A chandelier consists of multipl ...
- 学习bash——变量
一.什么是变量 变量:一个字眼,用来替代另一个比较复杂或者是容易变动的数据. 变量的优势:可变性.方便性 二.变量内容的设置 关键词:变量,变量名称,变量的内容(我默认将变量与变量名称等价) 方法:变 ...
- Flink on yarn的问题:Invalid AMRMToken
目前采用的Flink的版本是1.4.2,运行在yarn上,总是时不时的报错“Invalid AMRMToken from appattempt”,导致AM挂掉. 简而言之,就是AM和RM沟通的过程中, ...
- ob_flush()和flush()的区别
最近写定时任务,遇到ob_flush()和flush()混淆的问题... ob_flush/flush在手册中的描述, 都是刷新输出缓冲区, 并且还需要配套使用, 所以会导致很多人迷惑- 其实, 他们 ...
- [LeetCode] 65. Valid Number(多个标志位)
[思路]该题题干不是很明确,只能根据用例来理解什么样的字符串才是符合题意的,本题关键在于几个标志位的设立,将字符串分为几个部分,代码如下: class Solution { public: strin ...