Word Search II
2015-05-31 16:33
134 查看
Word Search II
问题:
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
思路:
回溯
我的代码:
View Code
学习之处:
思路很简单,就是回溯,但是有一点需要自己学习,由于会有重复的结果,所以在我的代码里面需要加入 if(!list.contains(word))的判断以确定是否添加到结果List里面,但是在别人代码里面是用的Set<String> res = new HashSet<String>(); 这样直接过滤掉了重复的结果,如此一来节约了不少时间,最后再用return new ArrayList<String>(res);将set转换成List,完工!
问题:
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
思路:
回溯
我的代码:
ublic class Solution { Set<String> res = new HashSet<String>(); public List<String> findWords(char[][] board, String[] words) { Trie trie = new Trie(); for (String word : words) { trie.insert(word); } int m = board.length; int n = board[0].length; boolean[][] visited = new boolean[m] ; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { dfs(board, visited, "", i, j, trie); } } return new ArrayList<String>(res); } public void dfs(char[][] board, boolean[][] visited, String str, int x, int y, Trie trie) { if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return; if (visited[x][y]) return; str += board[x][y]; if (!trie.startsWith(str)) return; if (trie.search(str)) { res.add(str); } visited[x][y] = true; dfs(board, visited, str, x - 1, y, trie); dfs(board, visited, str, x + 1, y, trie); dfs(board, visited, str, x, y - 1, trie); dfs(board, visited, str, x, y + 1, trie); visited[x][y] = false; } }
View Code
学习之处:
思路很简单,就是回溯,但是有一点需要自己学习,由于会有重复的结果,所以在我的代码里面需要加入 if(!list.contains(word))的判断以确定是否添加到结果List里面,但是在别人代码里面是用的Set<String> res = new HashSet<String>(); 这样直接过滤掉了重复的结果,如此一来节约了不少时间,最后再用return new ArrayList<String>(res);将set转换成List,完工!
相关文章推荐
- js正则表达式总结
- vim列编辑模式
- 3D数学之-向量矩阵欧拉角和四元数
- <深入理解JavaScript>学习笔记(3)_全面解析Module模式
- 获取数据源数据的实现---Architecting Android
- 使用MyBatis Generator自动生成DAO以及实体类
- JAVA编程思想学习总结:第十三章字符串
- mysql 查询执行的流程
- BZOJ_1001 狼抓兔子
- java 打包 编译
- 实现多线程
- Android应用层View绘制流程与源码分析
- JAVA 单例设计模式
- PIE使IE支持CSS3圆角盒阴影与渐变渲染
- C++ 学习笔记(四) GCC常用参数
- 使用Python爬虫爬取妹子图图片
- [Lintcode] Maximum Gap Problem
- [Unity基础]打包与读取AssetBundle
- CreateFile 打开 I/O device
- 疯狂Java学习笔记(63)-----------线程进阶