【leetcode】Word Ladder II(hard)★ 图 回头看
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 = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
思路:
我自己用回溯做,结果超时了。代码和注释如下: 很长
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_set>
#include <string>
using namespace std; class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> ans;
vector<string> hash; //记录单词是否已经生成
vector<string> X;
vector<vector<string>> S;
vector<int> hashlength; //记录在k = 0 - ... 时 hash 的长度 方便弹出 int minlen = ;
int k = ;
hash.push_back(start);
hashlength.push_back();
if(S.size() <= k)
{
S.push_back(vector<string>());
}
S[k].push_back(start); while(k >= )
{
while(!S[k].empty())
{
X.push_back(S[k].back());
S[k].pop_back(); if(onedifferent(X.back(), end))
{
X.push_back(end);
if(k == minlen) //只存长度最短的
{
ans.push_back(X);
}
if(k < minlen) //如果有新的最短长度 ans清空,压入新的最短答案
{
minlen = k;
ans.clear();
ans.push_back(X);
}
}
else if(k < minlen) //k如果>= minlen 那么后面的结果肯定大于最短长度
{
k++;
if(S.size() <= k) //如果S的长度不够 扩大S长度
{
S.push_back(vector<string>());
}
if(hashlength.size() <= k)//如果hashlength的长度不够 扩大其长度
{
hashlength.push_back();
}
unordered_set<string>::iterator it;
for(it = dict.begin(); it != dict.end(); it++) //对字典中的数字遍历,得到下一个长度可以用的备选项
{
if(onedifferent(X.back(), *it) && (find(hash.begin(), hash.end(), *it) == hash.end()))
{
hashlength[k]++;
hash.push_back(*it);
S[k].push_back(*it);
}
}
}
}
k--;
while(k >= && hashlength[k]) //把当前层压入hash的值都弹出
{
hash.pop_back();
hashlength[k]--;
}
while(k >= && X.size() > k) //把当前层压入X的值弹出
{
X.pop_back();
}
} return ans;
} bool onedifferent(string s1, string s2) //判断s1是否可以只交换一次得到s2
{
int diff = ;
for(int i = ; i < s1.size(); i++)
{
if(s1[i] != s2[i])
diff++;
}
return (diff == );
}
}; int main()
{
Solution s;
unordered_set<string> dict;
dict.insert("hot");
dict.insert("dot");
dict.insert("dog");
dict.insert("lot");
dict.insert("log"); string start = "hit";
string end = "cog"; vector<vector<string>> ans = s.findLadders(start, end, dict); return ;
}
别人的思路:我没怎么看,只知道是用图的思想 速度也不快 差不多1000ms的样子
class Solution {
public:
vector<vector<string>> helper(unordered_map<string,vector<string>> &pre,string s,unordered_map<string,int>&visit,string start){
vector<vector<string> > ret,ret1;vector<string> t_ret;
if(s==start) {t_ret.push_back(s);ret.push_back(t_ret);return ret;}
for ( auto it = pre[s].begin(); it != pre[s].end(); ++it ){
ret1=helper(pre,*it,visit,start);
for(int i=;i<ret1.size();i++){
ret1[i].push_back(s);
ret.push_back(ret1[i]);
} ret1.clear();
}
return ret;
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
unordered_map<string,vector<string> > graph;unordered_map<string,int> visit;unordered_map<string,vector<string>> pre;
vector<vector<string> > ret; vector<string> t_ret;
if(start==end){t_ret.push_back(start);t_ret.push_back(end);ret.push_back(t_ret);return ret;}
dict.insert(start);dict.insert(end);
for ( auto it = dict.begin(); it != dict.end(); ++it ){
string t=*it; visit[t]=;
for(int i=;i<t.size();i++)
for(int j='a';j<='z';j++){
if(char(j)==t[i]) continue;
string tt=t;
tt[i]=char(j);
if(dict.count(tt)>) graph[t].push_back(tt);
}
}
queue <string> myq;
myq.push(start);
while(!myq.empty()){
for(int i=;i<graph[myq.front()].size();i++){
if( visit[graph[myq.front()][i]]==){
visit[graph[myq.front()][i]]=visit[myq.front()]+;
myq.push(graph[myq.front()][i]);
pre[graph[myq.front()][i]].push_back(myq.front());
}
else if(visit[graph[myq.front()][i]]>&&visit[graph[myq.front()][i]]>=visit[myq.front()]+){
if(visit[graph[myq.front()][i]]>visit[myq.front()]+){
visit[graph[myq.front()][i]]=visit[myq.front()]+;
pre[graph[myq.front()][i]].push_back(myq.front());
}else pre[graph[myq.front()][i]].push_back(myq.front());;
}
}
visit[start]=;
myq.pop();
}
if(visit[end]==) return ret;
ret=helper(pre,end,visit,start);
return ret;
}
};
【leetcode】Word Ladder II(hard)★ 图 回头看的更多相关文章
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode: Word Ladder II [127]
[题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- leetcode—word ladder II
1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...
- [LeetCode] Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- [Leetcode Week5]Word Ladder II
Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
随机推荐
- Session id实现通过Cookie来传输方法及代码参考
1. Web中的Session指的就是用户在浏览某个网站时,从进入网站到浏览器关闭所经过的这段时间,也就是用户浏览这个网站所花费的时间.因此从上述的定义中我们可以看到,Session实际上是一个特定的 ...
- oracle开启audit(审计)
1.查看审计功能是否开启(本机已经开启,如果audit_sys_operations值为FALSE就是没开审计) [sql] view plaincopyprint? SQL> CONN /AS ...
- jQuery实现CheckBox全选、全不选
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Android开发之如何保证Service不被杀掉(前台服务)
序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作,都要保证service不被kill.参考了现今各种定制版的系统和安全厂商牛虻软件,如何能保证自 ...
- private继承
private继承并不如public继承一样具有is-a的关系. ------------------------------------------------------------------- ...
- HR不会告诉你的秘密
原文转载自http://blog.csdn.net/happy08god/article/details/5534326 下面,只是摘出来一些基本的观点. 1. 入职时的工资高低不重要,只要你努力工作 ...
- PHP 反射 ReflectionClass
今天遇到了这样一个问题,如下代码: classA.php <?php class ClassA{ public function funcAa(){ } public function func ...
- 简单使用packetbeat
简单使用packetbeat 标签:packetbeat elasticsearch 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在前面两篇文章中记录了使用logstash来收集mysql的慢 ...
- php100 编程小技巧
用单引号代替双引号来包含字符串,这样做会更快一些.因为PHP会在双引号包围的字符串中搜寻变量,单引号则 不会,注意:只有echo能这么做,它是一种可以把多个字符串当作参数的“函数”(译注:PHP手册中 ...
- wireshark总结
拖延了两个月的总结!下面的很大一部分来自其它博客. wireshark过滤器的区别 捕捉过滤器(CaptureFilters):用于决定将什么样的信息记录在捕捉结果中.需要在开始捕捉前设置.在Capt ...