Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. 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)★ 图 回头看的更多相关文章

  1. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  2. LeetCode :Word Ladder II My Solution

    Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start  ...

  3. LeetCode: Word Ladder II 解题报告

    Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...

  4. [LeetCode] Word Ladder II 词语阶梯之二

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  5. LeetCode: Word Ladder II [127]

    [题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  6. leetcode—word ladder II

    1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...

  7. [LeetCode] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  8. LeetCode:Word Ladder I II

    其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...

  9. [Leetcode Week5]Word Ladder II

    Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...

  10. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

随机推荐

  1. php对UTF8字体串进行单字分割返回数组

    在网上查了很多字符串分割方法,都无法正确对UTF8字符串进行正确分割返回单个字符的数组.经过对FTU8编码的分析写出了下面的方法对UTF8进行分割.本人测试可用.本方法只支持UTF8编码的,其它编码转 ...

  2. 20141015--for语句2

    for语句,打印等腰三角形: 第一种方法:(使用for语句嵌套) 第二种方法:(定义string型变量) 以下是其他形状的等腰三角形: (穿插使用了for语句嵌套,定义string型)

  3. spring aop配置及用例说明(4)

    欢迎交流转载:http://www.cnblogs.com/shizhongtao/p/3476161.html 这里简单对xml的配置方式做一下描述.代码还是上一篇(http://www.cnblo ...

  4. c#基础汇总-------------封装

    说到封装,其实是比较基础类的问题,它为程序设计提供了系统与系统,模块与模块,类与类之间交互的实现手段.在.Net中,一切看起来都已经被包装在.Net FrameWork这一复杂的网络中,提供给最终开发 ...

  5. flex&bison 1

    .   {ECHO;}-----单独的flex使用中有效 .   { yyerror();}--------flex和bison交叉使用,即使不调用yyerror函数,也会报错的 error: syn ...

  6. PHP 反射 ReflectionClass

    今天遇到了这样一个问题,如下代码: classA.php <?php class ClassA{ public function funcAa(){ } public function func ...

  7. Memcached的安装(Linux)、操作、命令

    最近在整理有关分布式缓存的服务器,做了一下老牌nosql服务器memcached的学习总结.文中所述的所有安装均是在联网的情况下进行的. 序: 什么是memcached: Free & ope ...

  8. 一些dos命令

    MS DOS 命令大全 一.基础命令 1 dir 无参数:查看当前所在目录的文件和文件夹. /s:查看当前目录已经其所有子目录的文件和文件夹. /a:查看包括隐含文件的所有文件. /ah:只显示出隐含 ...

  9. ios 数字禁止变成电话号码

    1.使用meta来限制页面不转换电话号码   <meta name="format-detection"content="telphone=no"/> ...

  10. 静态页面中如何传json数据

    首页传递参数组装成json数据,再编码 var param="{type:'"+type+"',text:'"+select_text+"',sele ...