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基础(1)-几种获取类的扩展方式
摘要 在日常开发过程中经常需要获取类的扩展集.即获取类的子类集(抽象类),或者接口实现类.比如说状态模式中,状态构建类,策略模式中的,策略构造方式.本文介绍几种获取方式. 实现 以策略模式为例 定义了 ...
- 深入理解计算机系统 BombLab 实验报告
又快有一个月没写博客了,最近在看<深入理解计算机系统>这本书,目前看完了第三章,看完这章,对程序的机器级表示算是有了一个入门,也对 C 语言里函数栈帧有了一个初步的理解. 为了加深对书本内 ...
- Python自学day-1
一.Python介绍 1.python擅长领域: WEB开发:Django. pyramid. Tornado. Bottle. Flask. WebPy 网络编程:Twisted(牛 ...
- ZooKeeper学习之路(四)—— Java 客户端 Apache Curator
一.基本依赖 Curator是Netflix公司开源的一个Zookeeper客户端,目前由Apache进行维护.与Zookeeper原生客户端相比,Curator的抽象层次更高,功能也更加丰富,是目前 ...
- web交互方式---ajax
知识不怕旧,关键在于在旧知识的基础上不断创新与提高! 引入一个问题:打开一个浏览器,在地址栏输入一个网址,按下 enter 键到看到整个页面,中间都经历了哪些事情? 这是一个前端的面试题,相信很多朋友 ...
- python的is与==的区别
is is比较的是两个变量的地址值,如果地址值正确,则返回True,否则返回False,实例如下: 如图所示,a,b列表的数值相等,但地址是不相等的,所以返回True,与值无关 == ==比较的是两个 ...
- 并发编程-concurrent指南-计数器CountDownLatch
java.util.concurrent.CountDownLatch 是一个并发构造,它允许一个或多个线程等待一系列指定操作的完成. CountDownLatch 以一个给定的数量初始化.count ...
- Facebook也炒币吗?Libra币是什么?
Facebook 在上周发布了加密数字货币,称为 Libra币. 太火爆了,很多人都在关注和讨论,包括一些科技大佬们都很积极的讨论(当然,这里指的是真正的科技大佬,比如 马化腾.王兴等,而不是指哪些割 ...
- [golang]golang time.After内存泄露问题分析
无意中看到一篇文章说,当在for循环里使用select + time.After的组合时会产生内存泄露,于是进行了复现和验证,以此记录 内存泄露复现 问题复现测试代码如下所示: package mai ...
- Android native进程间通信实例-socket本地通信篇之——基本通信功能
导读: 网上看了很多篇有关socket本地通信的示例,很多都是调通服务端和客户端通信功能后就没有下文了,不太实用,真正开发中遇到的问题以及程序稳定性部分没有涉及,代码健壮性不够,本系列(socket本 ...