leetcode:查找
2016-04-07 15:30
141 查看
1. word ladder
题目:Given two words (start and end), and a dictionary, find the length of shortest transformation sequence 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"]
As one shortest transformation is
"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length
5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
题解:
这道题是套用BFS同时也利用BFS能寻找最短路径的特性来解决问题 。所有的变化情况联系起来就是一棵树, 相当于从根结点start出发寻找特定的节点end。
把每个单词作为一个node进行BFS。当取得当前字符串时,对他的每一位字符进行从a~z的替换,如果在字典里面,就入队,并将下层count++,并且为了避免环路,需把在字典里检测到的单词从字典里删除。这样对于当前字符串的每一位字符安装a~z替换后,在queue中的单词就作为下一层需要遍历的单词了。
正因为BFS能够把一层所有可能性都遍历了,所以就保证了一旦找到一个单词equals(end),那么return的路径肯定是最短的。
像给的例子 start = hit,end = cog,dict = [hot, dot, dog, lot, log]
按照上述解题思路的走法就是:
level = 1 hit dict = [hot, dot, dog, lot, log]
ait bit cit ... xit yit zit , hat hbt hct ... hot ... hxt hyt hzt , hia hib hic ... hix hiy hiz
level = 2 hot dict = [dot, dog, lot, log]
aot bot cot dot ... lot ... xot yot zot,hat hbt hct ... hxt hyt hzt,hoa hob hoc ... hox hoy hoz
level = 3 dot lot dict = [dog log]
aot bot ... yot zot,dat dbt ...dyt dzt,doa dob ... dog .. doy doz,
aot bot ... yot zot,lat lbt ... lyt lzt,loa lob ... log... loy loz
level = 4 dog log dict = []
aog bog cog
level = 5 cog dict = []
public ArrayList<String> generateParenthesis(int n) { ArrayList<String> res = new ArrayList<String>(); String item = new String(); if (n<=0) return res; dfs(res,item,n,n); return res; } // item保存上一步的临时结果,res最终结果; leftt,right指示搜索层级变化 public void dfs(ArrayList<String> res, String item, int left, int right){ if(left > right)//deal wiith ")(" return; if (left == 0 && right == 0){ res.add(new String(item)); return; } if (left>0) dfs(res,item+'(',left-1,right); if (right>0) dfs(res,item+')',left,right-1); }
View Code
相关文章推荐
- MySql 优化
- 纠结很久的问题 在SSH下,Dao Service 下 baseService 为NULL的问题
- java解析ajax之json字符串
- adb工具(通用的调试工具、debug工具)&操作命令详解
- leetcode笔记:Counting Bits
- AndroidStudio 文档自动提示突然消失,怎么解决?
- 各大网站CSS代码初始化集合
- python 列表、元组、字典
- FILE 结构体及缓冲区
- WEB免费打印控件推荐
- C++实现——大数乘以小数
- 6.8.3 qmgr_job_entry_select函数:选择QMGR_JOB、QMGR_PEER、QMGR_ENTRY结构体
- SQL Server 事务、异常和游标
- WEB免费打印控件推荐
- Mysql 中 iddata1的缩小步骤
- 游戏开发数值经验设计(10)
- Linux的进程/线程间通信方式总结 04
- 邮箱大师添加outlook2010 方法 图文详解
- iOS - QRCode(二维码)的生成和识别
- 6.8.2 qmgr_transport_select函数: 选择QMGR_TRANSPORT 与round borin策略