作者: 负雪明烛
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+)的更多相关文章

  1. 【LeetCode】90. Subsets II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 回溯法 日期 题目地址:https://leet ...

  2. 【LeetCode】47. Permutations II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:htt ...

  3. 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...

  4. 【LeetCode】92. Reverse Linked List II 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 题目地址:https://leet ...

  5. 【LeetCode】82. Remove Duplicates from Sorted List II 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/remove-du ...

  6. 【LeetCode】275. H-Index II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/h-index- ...

  7. 【LeetCode】454. 4Sum II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcod ...

  8. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

  9. LeetCode: Pascal's Triangle II 解题报告

    Pascal's Triangle II Total Accepted: 19384 Total Submissions: 63446 My Submissions Question Solution ...

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

随机推荐

  1. 数据库(database)介绍

    0.数据定义:除了文本类型的数据,图像.音乐.声音都是数据. 数据分类:结构化数据.非结构化数据.1.数据库定义:"电子化的文件柜","数据仓库".数据库是一个 ...

  2. .net与java建立WebService再互相调用

    A: .net建立WebService,在java中调用. 1.在vs中新建web 简单修改一下Service.cs的[WebMethod]代码: using System; using System ...

  3. day11 系统安全

    day11 系统安全 复习总结 文件 1.创建 格式:touch [路径] [root@localhost ~]# touch 1.txt # 当前路径创建 [root@localhost ~]# t ...

  4. OpenStack之八: network服务(端口9696)

    注意此处用的一个网络,暂时不用启动第二个网官网地址 https://docs.openstack.org/neutron/stein/install/controller-install-rdo.ht ...

  5. Java_zip_多源文件压缩到指定目录下

    依赖: <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress --> <depend ...

  6. C语言static关键字

    C语言static关键字 static关键字的作用,主要从在程序的生存周期.作用域和在代码段中的位置起作用. 全局变量 静态全局变量 局部变量 静态局部量 生存周期 程序运行到结束 程序运行到结束 函 ...

  7. 利用代码覆盖率提高嵌入式软件的可靠性 - VectorCAST

    简介 代码覆盖率是衡量软件测试完成情况的指标,通常基于测试过程中已检查的程序源代码比例 计算得出.代码覆盖率可以有效避免包含未测试代码的程序被发布. 代码覆盖率能不能提高软件的可靠性?答案是肯定的,代 ...

  8. DT10功能介绍--DT10多波示波器

    功能介绍 有些嵌入式软件方面的问题,利用传统的调试器可能无法解决,而通过逻辑分析器则能有效地解决.请仔细阅读本文, 看我们如何一步一步地讲解在这种情况下所需的配置. 但是,从传统意义上讲,逻辑分析器是 ...

  9. SQLserver 2014 如何使用Datename()函数获取对应时间

    一.在本文中,GetDate()获得的日期由两部分组成,分别是今天的日期和当时的时间: Select GetDate() 二.用DateName()就可以获得相应的年.月.日,然后再把它们连接起来就可 ...

  10. dart系列之:浏览器中的舞者,用dart发送HTTP请求

    目录 简介 发送GET请求 发送post请求 更加通用的操作 总结 简介 dart:html包为dart提供了构建浏览器客户端的一些必须的组件,之前我们提到了HTML和DOM的操作,除了这些之外,我们 ...