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的更多相关文章

  1. 关于Backtracing中有重复元素的处理办法

    backtracing是一个常用的解法.之前遇到一个题目,求一个集合的子集, 例如给定{1,2,3,4,5},求其大小为3的子集. 利用backtracing可以较快的给出答案. 然而,该题还有一个变 ...

  2. net-force.nl/programming writeup

    从 wechall.net 到 net-force.nl 网站,发现网站的内容不错,里面也有不同类型的挑战题目:Javascript / Java Applets / Cryptography / E ...

  3. leetcode bugfree note

    463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...

  4. 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 ...

  5. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  6. 【LeetCode题意分析&解答】39. Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...

  7. 【LeetCode题意分析&解答】37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  8. redis的管理工具

    phpredisadmin工具 rdbtools管理工具 saltstack管理redis 通过codis完成redis管理 一:phpredisadmin工具:类似于mysqladmin管理mysq ...

  9. Redis【第一篇】安装

    第一步:准备 1. 操作系统 CentOS-7-x86_64-Everything-1511 2. redis 版本 redis-3.2.8 3. 修改内核参数 有三种方式: 1)编辑/etc/sys ...

随机推荐

  1. vue.js与后台模板引擎“双花括号”冲突时的解决办法

    后台渲染模板如swig,也使用“{{ }}“作为渲染,与前端vue的产生冲突,此时只要在新建Vue对象时,添加delimiters: ['${', '}'],就搞定了,代码如下 <!DOCTYP ...

  2. Mybatis_three

    延迟加载 实现多对一的延迟加载(association) 例如下面的:有很多个账户信息(招商\工商\农商)是属于一个用户人的 [需求] 查询账户(Account)信息并且关联查询用户(User)信息. ...

  3. 【UVA - 11624】Fire!

    -->Fire! 直接上中文 Descriptions: 乔在迷宫中工作.不幸的是,迷宫的一部分着火了,迷宫的主人没有制定火灾的逃跑计划.请帮助乔逃离迷宫.根据乔在迷宫中的位置以及迷宫的哪个方块 ...

  4. SSM(四)Mybatis延迟加载

    1.概念 MyBatis中的延迟加载,也称为懒加载,是指在进行关联查询时,按照设置延迟加载规则推迟对关联对象的select查询.延迟加载可以有效的减少数据库压力. 2.关联对象的加载时机 ①.直接加载 ...

  5. esxi开启SSH

  6. hiccup和Latch off

    hiccup(Constant-Current)和Latch off 限电流保护的两种形式 hiccup:一种是以恒定电流存在,这种一般是可恢复的,当故障解除后自动恢复: Latch off:一种是锁 ...

  7. python基本数据类型之数字类型和其相关运算

    数字(number) Python3 支持 int.float.bool.complex(复数). 在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long. ...

  8. AntD使用timePiacker封装时间范围选择器(React hook版)

    .katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...

  9. HDU 5775:Bubble Sort(树状数组)

    http://acm.hdu.edu.cn/showproblem.php?pid=5775 Bubble Sort Problem Description   P is a permutation ...

  10. scrapy基础知识之 RedisCrawlSpider:

    这个RedisCrawlSpider类爬虫继承了RedisCrawlSpider,能够支持分布式的抓取.因为采用的是crawlSpider,所以需要遵守Rule规则,以及callback不能写pars ...