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 ...
随机推荐
- python 之 面向对象基础(定义类、创建对象,名称空间)
第七章面向对象 1.面向过程编程 核心是"过程"二字,过程指的是解决问题的步骤,即先干什么再干什么 基于该思想编写程序就好比在编写一条流水线,是一种机械式的思维方式 优点:复杂的问 ...
- 阿里云主机CentOS7设置远程连接MySQL数据库
有一个困扰了我好久的问题,今天终于解决了. 看网上的答案只有一部分.今天把完整的发篇博客纪念一下下. 首先,连接阿里云主机并登录数据库, 1.添加一个Host mysql>select User ...
- 中转Webshell 绕过安全狗(二)
前言 在实践中转webshell绕过安全狗(一)中,在服务端和客户端均为php.某大佬提示并分享资源后,打算使用python完成中转.部分代码无耻copy. 客户端 本地127.0.0.1,安装pyt ...
- php中使用trait设计单例
trait Singleton { private static $instace = null; private function __construct() { } private functio ...
- (数据科学学习手札62)详解seaborn中的kdeplot、rugplot、distplot与jointplot
一.简介 seaborn是Python中基于matplotlib的具有更多可视化功能和更优美绘图风格的绘图模块,当我们想要探索单个或一对数据分布上的特征时,可以使用到seaborn中内置的若干函数对数 ...
- Linux命令分类汇总(1~6)
Linux命令分类汇总 序号 命令 参数 英文释义 功能说明 (一)线上查询及帮助命令(2个) 1 man manual 查看命令帮助,命令的词典,还有info 2 help h 查看Linux内置命 ...
- kubernetes实战篇之helm使用技巧
系列目录 使用压缩包安装chart 我们使用helm package打包的时候,默认会在当前位置生成一个tgz压缩包,然后helm把它复制到到$HOME/.helm/repository目录下,现在还 ...
- Python开发【第七篇】: 面向对象和模块补充
内容概要 特殊成员 反射 configparser模块 hashlib模块 logging模块 异常处理 模块 包 1. 特殊成员 什么是特殊成员呢? __init_()就是个特殊的成员. 带双下划线 ...
- 前端摸爬滚打之路(一)之 JavaScript 基础
前言:这是我第一次在博客上记录自己的前端学习过程,以往都是在桌面右侧开个 onenote 小窗,记录自己在学习过程中获得的知识.通常都是记录的满满当当,然后心满意足的关闭窗口,但是记录不代表学会.这些 ...
- Numpy之数组创建
ndarray 数组除了可以使用 ndarray 构造器来创建外,也可以通过如下方式创建. 一.创建数组 numpy.empty 语法: numpy.empty(shape, dtype = floa ...