【LeetCode】52. N-Queens II 解题报告(Python & C+)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/n-queens-ii/description/
题目描述
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
题目大意
求n皇后问题解的个数。注意题意,n皇后问题是在n*n的棋盘上放n个皇后,有多少种做法。
解题方法
全排列函数
纯暴力解法。因为皇后每行只能有一个,所以用一个数组来保存第i行的皇后处的列号。然后对这个排列进行判断,是否满足条件。判断的依据是,我们已经知道了皇后不在同行同列,因此只需要判断是否在斜着的就行。
当n=9的时候超时,这个方法直接给它返回了352这个结果。。
from itertools import permutations
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
if n == 9: return 352
def canBe(nums):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if i - j == nums[i] - nums[j] or j - i == nums[i] - nums[j]:
return False
return True
columnIndex=range(0, n)
permutation=list(permutations(columnIndex, n))
return sum(map(canBe,permutation))
回溯法
这个题最好的做法还是回溯法。怎么个思路呢?我们只需要一个一维数组,含义是第i行放在了哪一列上,如果这行没有放,那么就设置成默认值-1。现在我们需要使用回溯法,对第row行进行放置(前row-1行已经放置好了)。如果第row行放在第col列成功了,就继续搜索第row+1行,否则就回溯放到第col+1列试试。
注意判断第row行放置第col列情况下能否成功呢?要在前面找是不是和col同列的,或者斜着的:斜率的绝对值是1.
C++代码如下:
class Solution {
public:
int totalNQueens(int n) {
// vector[i] means the col number of row i
vector<int> board(n, -1);
int res = 0;
helper(board, 0, res);
return res;
}
// how many answers for cur row.(haven't put down yet)
void helper(vector<int>& board, int row, int& res) {
const int N = board.size();
if (row == N) {
res ++;
return;
} else {
for (int col = 0; col < N; col++) {
board[row] = col;
if (isValid(board, row, col)) {
helper(board, row + 1, res);
}
board[row] = -1;
}
}
}
// already put down on [row, col]
bool isValid(vector<int>& board, int row, int col) {
for (int prow = 0; prow < row; prow++) {
int pcol = board[prow];
if (pcol == -1 || col == pcol || abs(pcol - col) == abs(prow - row))
return false;
}
return true;
}
};
日期
2018 年 3 月 11 日
2018 年 12 月 23 日 —— 周赛成绩新高
【LeetCode】52. N-Queens II 解题报告(Python & C+)的更多相关文章
- 【LeetCode】90. Subsets II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 回溯法 日期 题目地址:https://leet ...
- 【LeetCode】47. Permutations II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:htt ...
- 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...
- 【LeetCode】92. Reverse Linked List II 解题报告(Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 题目地址:https://leet ...
- 【LeetCode】82. Remove Duplicates from Sorted List II 解题报告(Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/remove-du ...
- 【LeetCode】275. H-Index II 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/h-index- ...
- 【LeetCode】454. 4Sum II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcod ...
- 【LeetCode】62. Unique Paths 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...
- LeetCode: Pascal's Triangle II 解题报告
Pascal's Triangle II Total Accepted: 19384 Total Submissions: 63446 My Submissions Question Solution ...
- LeetCode: Linked List Cycle II 解题报告
Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cyc ...
随机推荐
- Python函数之传参
目录 1. 函数传参 1.1 参数的作用 1.2 形参和实参 1.3 位置参数 1.4 关键字参数 1.5 默认实参 1.6 参数总结 2. 可变参数 1. 函数传参 1.1 参数的作用 1.2 形参 ...
- mongodb存储的基本使用
Python连接mongodb一般使用pymongo模块 1. pymongo模块的简单使用 ### MongoDB存储 ## 连接MongoDB import pymongo # 建立连接对象,2种 ...
- C语言中内存对齐与结构体
结构体 结构体是一种新的数据类型,对C语言的数据类型进行了极大的扩充. struct STU{ int age; char name[15]; }; struct STU a; //结构体实例 str ...
- Go 性能提升tips--边界检查
1. 什么是边界检查? 边界检查,英文名 Bounds Check Elimination,简称为 BCE.它是 Go 语言中防止数组.切片越界而导致内存不安全的检查手段.如果检查下标已经越界了,就会 ...
- 理解ASP.NET Core - 模型绑定&验证(Model Binding and Validation)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 模型绑定 什么是模型绑定?简单说就是将HTTP请求参数绑定到程序方法入参上,该变量可以是简单类 ...
- day04 查找关键字
day04 查找关键字 昨日内容回顾 基本数据类型之日期相关类型 date :年月日 time :时分秒 datetime:年月日时分秒 year :年 基本数据类型之枚举与集合类型 # 枚举 多选一 ...
- Virtual functions in derived classes
In C++, once a member function is declared as a virtual function in a base class, it becomes virtual ...
- Dubbo消费者异步调用Future使用
Dubbo的四大组件工作原理图,其中消费者调用提供者采用的是同步调用方式.消费者对于提供者的调用,也可以采用异步方式进行调用.异步调用一般应用于提供者提供的是耗时性IO服务 一.Future异步执行原 ...
- 关系型数据库和非关系型数据库区别、oracle与mysql的区别
一.关系型数据库 关系型数据库,是指采用了关系模型来组织数据的数据库. 关系模型是在1970年由IBM的研究员E.F.Codd博士首先提出的,在之后的几十年中,关系模型的概念得到了充分的发展并逐 ...
- AOP中环绕通知的书写和配置
package com.hope.utils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotatio ...