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. SharpZipLib 压缩后传输给第三方平台无法识别问题

    问题描述:在项目中需要将文件压缩然后传输给三方进行彩信发送,使用SharpZipLib 进行压缩,原先使用J#进行压缩处理,但是用SharpZipLib压缩后的zip文件传输过去之后,总会报发送失败. ...

  2. Spring使用总结

    一.基础JAR包 spring-beans.jar spring-context.jar spring-core.jar spring-expression.jar 二.XML的配置 1.一级结构 & ...

  3. Unity3D项目实战笔记(5):延时功能的几种实现

    我所做过的系统,分单机版系统(2005年).CS系统(2010年).实时系统(2015年),各个系统均有“延时”功能:定时调度的: 本博客说的是实时系统中的延时功能(基于Unity3D游戏引擎). 在 ...

  4. 为什么要使用jQuery?

    首先必须得了解为什么要学习JQuery,JQuery有哪些优点,当然是相对于传统的Javascript和DOM来说了,现在将JQuery的优势总结如下: 1,轻量级. JQuery非常小,压缩包只有1 ...

  5. Apache 使用密码文件验证用户

    使用文本文件作为密码文件 创建密码文件 需要使用htpasswd.exe文件来创建用户密码文件 语法: htpasswd -c '文件完整路径' 用户名 向一个用户密码文件中添加一个新用户 语法: h ...

  6. spring aop配置及用例说明(2)

    欢迎交流转载:http://www.cnblogs.com/shizhongtao/p/3473362.html 这里先介绍下几个annotation的含义, @Before:表示在切入点之前执行. ...

  7. PHP中使用多线程

    <?php while(1)//循环采用3个进程 { //declare(ticks=1); $bWaitFlag= FALSE; // 是否等待进程结束 //$bWaitFlag = TRUE ...

  8. PCB优化设计(二) 转载

    PCB优化设计(二) 2011-04-25 11:41:05|  分类: PCB设计   目 前SMT技术已经非常成熟,并在电子产品上广泛应用,因此,电子产品设计师有必要了解SMT技术的常识和可制造性 ...

  9. Linux VM 设置静态ip地址上网

    因为是路由器共享上网,VM每次都是通过DHCP方式自动获取ip地址,连接Linux VM时ip地址经常变,很麻烦.现在把VM设置静态ip的方法总结一下,以免以后忘了. 1. VM上网方式设置为桥接. ...

  10. JAVA中的各种 哈希码(HashCode) 与 equals方法在HIBERNATE的实际应用[转载]

    1.什么是哈希码(HashCode) 在Java中,哈希码代表对象的特征.例如对象 Java代码 String str1 = “aa”, str1.hashCode= 3104 String str2 ...