backtracing
5月10日
1 37 Sudoku Slover
public void solveSudoku(char[][] board) {
if(board == null || board.length == 0)
return;
slove(board);
}
public boolean slove(char[][] board){
for (int i = 0; i < board.length; i++)
{
for (int j = 0; j < board[0].length; j++)
{
if (board[i][j] == '.')
{
for (char c = '1'; c <= '9'; c++)
{
if (isValue(board, i, j, c))
{
board[i][j] = c;
if (slove(board))
return true;
else
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
public boolean isValue(char[][] board, int row, int col, char c)
{
for (int i = 0; i < 9; i++)
{
if (board[i][col] != '.' && board[i][col] == c) return false;
if (board[row][i] != '.' && board[row][i] == c) return false;
if (board[3 * (row/3) + i/3][3 *(col/3) + i % 3] != '.' &&
board[3 * (row/3) + i/3][3 *(col/3) + i % 3] == c) return false;
}
return true;
}
2 51 N-Queens
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
help(n, 0, new int[n], res);
return res;
}
public void help(int n, int row, int[] colforrow, List<List<String>> res)
{
if (row == n)
{
ArrayList<String> item = new ArrayList<>();
for (int i = 0; i < n; i++)
{
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++)
{
if (colforrow[i] == j)
sb.append('Q');
else
sb.append('.');
}
item.add(sb.toString());
}
res.add(item);
return;
}
for (int i = 0; i < n; i++)
{
colforrow[row] = i;
if (check(row, colforrow))
{
help(n, row + 1, colforrow, res);
}
}
}
3 52 N-Queens II
public int totalNQueens(int n) {
ArrayList<Integer> res = new ArrayList<>();
res.add(0);
help(n, 0, new int[n], res);
return res.get(0);
}
private void help(int n, int row, int[] columnForRow, ArrayList<Integer> res)
{
if(row==n)
{
res.set(0,res.get(0)+1);
return;
}
for(int i=0;i<n;i++)
{
columnForRow[row]=i;
if(check(row,columnForRow))
{
help(n,row+1,columnForRow,res);
}
}
}
private boolean check(int row, int[] columnForRow)
{
for(int i=0;i<row;i++)
{
if(columnForRow[i]==columnForRow[row] || Math.abs(columnForRow[row]-columnForRow[i])==row-i)
return false;
}
return true;
}
4 77 combinations 分子问题
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if (n <= 0 || n < k) return res;
help(n, k, 1, new ArrayList<Integer>(), res);
return res;
}
public void help(int n, int k, int start, ArrayList<Integer> item, List<List<Integer>> res)
{
if (item.size() == k)
{
res.add(new ArrayList<Integer>(item));
return;
}
for (int i = start; i <= n; i++)
{
item.add(i);
help(n, k, i + 1, item, res);
item.remove(item.size() - 1);
}
}
5 89 Gray Code
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
res.add(0);
for (int i = 0; i < n; i++)
{
int size = res.size();
for (int k = size - 1; k >= 0; k--)
{
res.add(res.get(k)|1<<i);
}
}
return res;
}
6 211 Add and search Word
public class WordDictionary {
public class TrieNode{
public TrieNode[] children = new TrieNode[26];
public String item = "";
}
private TrieNode root = new TrieNode();
/** Initialize your data structure here. */
public WordDictionary() {
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray())
{
if (node.children[c - 'a'] == null)
{
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.item = word;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return match(word.toCharArray(), 0, root);
}
private boolean match(char[] chs, int k, TrieNode node)
{
if (k == chs.length) return !node.item.equals("");
if (chs[k] != '.')
{
return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k]-'a']);
}
else
{
for (int i = 0; i < node.children.length; i++)
{
if (node.children[i] != null)
{
if (match(chs, k + 1, node.children[i]))
return true;
}
}
}
return false;
}
}
7 212 Word Search II
Set<String> res = new HashSet<>();
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String str : words)
{
trie.insert(str);
}
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
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, int i, int j, String item, Trie trie)
{
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return;
if (visited[i][j]) return;
item += board[i][j];
if (!trie.startsWith(item)) return;
if (trie.search(item)) res.add(item);
visited[i][j] = true;
dfs(board, visited, i, j - 1, item, trie);
dfs(board, visited, i, j + 1, item, trie);
dfs(board, visited, i + 1, j, item, trie);
dfs(board, visited, i - 1, j, item, trie);
visited[i][j] = false;
}
backtracing的更多相关文章
- 关于Backtracing中有重复元素的处理办法
backtracing是一个常用的解法.之前遇到一个题目,求一个集合的子集, 例如给定{1,2,3,4,5},求其大小为3的子集. 利用backtracing可以较快的给出答案. 然而,该题还有一个变 ...
- net-force.nl/programming writeup
从 wechall.net 到 net-force.nl 网站,发现网站的内容不错,里面也有不同类型的挑战题目:Javascript / Java Applets / Cryptography / E ...
- leetcode bugfree note
463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...
- POJ #1015 - Jury Compromise - TODO: POJ website issue
(poj.org issue. Not submitted yet) This is a 2D DP problem, very classic too. Since I'm just learnin ...
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【LeetCode题意分析&解答】39. Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...
- 【LeetCode题意分析&解答】37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...
- redis的管理工具
phpredisadmin工具 rdbtools管理工具 saltstack管理redis 通过codis完成redis管理 一:phpredisadmin工具:类似于mysqladmin管理mysq ...
- Redis【第一篇】安装
第一步:准备 1. 操作系统 CentOS-7-x86_64-Everything-1511 2. redis 版本 redis-3.2.8 3. 修改内核参数 有三种方式: 1)编辑/etc/sys ...
随机推荐
- 玩转Java多线程(Lock.Condition的正确使用姿势)
转载请标明博客的地址 本人博客和github账号,如果对你有帮助请在本人github项目AioSocket上点个star,激励作者对社区贡献 个人博客:https://www.cnblogs.com/ ...
- 626. Exchange Seats-(LeetCode之Database篇)
问题表述 数据库表如下: id student 1 Abbot 2 Doris 3 Emerson 4 Green 5 Jeames 现在要通过SQL语句将表变换成如下: id student 1 D ...
- 【Shell学习笔记3》实践项目自动部署脚本】shell中获取返回值、获取当前sh文件路径
原创部分: 1.获取返回值 #This is a shell to Deploy Project #!/bin/bashcheck_results=`ps -ef | grep "java& ...
- Windows上安装PyV8
Windows上安装PyV8 在PyPi网站上有Windows的exe格式的包连接, PyPi, Google注意网络是否通畅! 官网地址 Google PyV8 双击安装, 注意, 一般会自动检测P ...
- 17 | 精益求精:聊聊提高GUI测试稳定性的关键技术
- python的is与==的区别
is is比较的是两个变量的地址值,如果地址值正确,则返回True,否则返回False,实例如下: 如图所示,a,b列表的数值相等,但地址是不相等的,所以返回True,与值无关 == ==比较的是两个 ...
- 研究Electron主进程、渲染进程、webview之间的通讯
背景 由于某个Electron应用,需要主进程.渲染进程.webview之间能够互相通讯. 不过因为Electron仅提供了主进程与渲染进程的通讯,没有渲染进程之间或渲染进程与webview之间通讯的 ...
- .Net项目中NLog的配置与使用
引言: 因为之前在项目开发中一直都是使用的Log4Net作为项目的日志记录框架,最近忽然感觉对它已经有点腻了,所以尝试着使用了NLog作为新项目的日志记录框架(当然作为一名有志向的攻城狮永远都不能只局 ...
- CS程序和BS程序文字转语音
一.项目中一直用到了文字转语音的功能,需求也比较简单,就是将一段报警信息通过语音的方式播放出来,之前一直采用CS客户端,利用微软自带的Speech语音播放库就可以完成, 1.1 封装winSpedk类 ...
- 绝对是全网最好的Splay 入门详解——洛谷P3369&BZOJ3224: Tyvj 1728 普通平衡树 包教包会
平衡树是什么东西想必我就不用说太多了吧. 百度百科: 一个月之前的某天晚上,yuli巨佬为我们初步讲解了Splay,当时接触到了平衡树里的旋转等各种骚操作,感觉非常厉害.而第二天我调Splay的模板竟 ...