leetcode — word-ladder-ii
import java.util.*;
/**
* Source : https://oj.leetcode.com/problems/word-ladder-ii/
*
*
* 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"]
* ]
*
* Note:
*
* All words have the same length.
* All words contain only lowercase alphabetic characters.
*
*/
public class WordLadder2 {
/**
* 在wordladder1的基础上,找到start到end的所有变化路径
*
* 这里需要回溯,采用深度优先DFS
*
* 优化:
* 因为这需要回溯,也就是说可能会重复计算某个单词的neighbors,所以可以实现将所有的单词构造成一棵树,就不需要每次计算neighbors
*
* @param start
* @param end
* @param dict
* @return
*/
public List<List<String>> findLadders (String start, String end, String[] dict) {
Set<String> set = new HashSet<String>(Arrays.asList(dict));
set.add(end);
List<List<String>> result = new ArrayList<List<String>>();
Set<String> list = new HashSet<String>();
list.add(start);
List<String> ladder = new ArrayList<String>();
recursion(list, end, ladder, result, set);
return result;
}
public void recursion (Set<String> list, String end, List<String> ladder, List<List<String>> result, Set<String> set) {
for (String str : list) {
ladder.add(str);
if (str.equals(end)) {
result.add(new ArrayList<String>(ladder));
}
Set<String> neighbors = findNeighbors(str,set);
recursion(neighbors, end, ladder, result, set);
set.addAll(neighbors);
ladder.remove(str);
}
}
private Set<String> findNeighbors (String cur, Set<String> dict) {
Set<String> neighbors = new HashSet<String>();
for (int i = 0; i < cur.length(); i++) {
for (int j = 0; j < 26; j++) {
char ch = (char) ('a' + j);
if (cur.charAt(i) != ch) {
String candidate = "";
if (i == cur.length()-1) {
candidate = cur.substring(0, i) + ch;
} else {
candidate = cur.substring(0, i) + ch + cur.substring(i+1);
}
if (dict.contains(candidate)) {
neighbors.add(candidate);
dict.remove(candidate);
}
}
}
}
return neighbors;
}
public static void print (List<List<String>> list) {
for (List<String> strList : list) {
System.out.println(Arrays.toString(strList.toArray(new String[strList.size()])));
}
}
public static void main(String[] args) {
WordLadder2 wordLadder2 = new WordLadder2();
String start = "hit";
String end = "cog";
String[] dict = new String[]{"hot","dot","dog","lot","log"};
print(wordLadder2.findLadders(start, end, dict));
}
}
leetcode — word-ladder-ii的更多相关文章
- [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
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- leetcode—word ladder II
1.题目描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence( ...
- 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 ...
随机推荐
- XIX Open Cup named after E.V. Pankratiev. GP of Poland(AMPPZ-2018)
A. Drone With a Camera 三分套三分. #include<cstdio> #include<cmath> #include<algorithm> ...
- 小白学习随笔the first week
The First Week 一.计算机基础 1.软件(应用程序) 2.解释器/编译器 - 解释型语言:将代码每一行传递给计算机一行,常用编程语言python,PHP,Ruby. - 编译型语言:将代 ...
- win10 音频设备图形隔离 占用CPU
这几天工作很烦!每次上班开机我的电脑就超级卡,自我感觉i7处理器加上8g内存应该杠杠的,打开任务管理器发现就不对了, 有“windows 音频设备图形隔离 ”这个进程吃了我20%的cpu,电脑的风扇也 ...
- python中的矩阵、多维数组
2. 创建一般的多维数组 import numpy as np a = np.array([1,2,3], dtype=int) # 创建1*3维数组 array([1,2,3]) type(a ...
- 对Jpa中Entity关系映射中mappedBy的理解
mappedBy 单向关系不需要设置该属性,双向关系必须设置,避免双方都建立外键字段数据库中1对多的关系,关联关系总是被多方维护的即外键建在多方,我们在单方对象的@OneToMany(mappedby ...
- LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation]
LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation] <c++> LeetCode 31 Next Pe ...
- C. Neko does Maths
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- 上传文件格式,及headers设置
file[]:(binary)文件格式,传过去的参数自然是query string parameters 形式,当然也有纯的formData格式 formData格式就是将所有的参数append到p ...
- vi 配置
vim ~/.vimrc source ~/.vimrc 添加相关配置 一直生效 0 行首 $ 行尾 spacebar 空格键: 合并多行 spaceba ...
- 1.7 All components require plug-in?
In Android, Activity, Service, ContentProvider, and BroadcastReceiver are called as four major compo ...