Problem
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 the number of distinct solutions to the n-queens puzzle.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Solution
Analysis
这道题的解法和51题相同,都是使用回溯法. 只不过这里,不需要记录所有可能的解,仅仅需要返回解的个数即可. 偷懒的话,可以直接使用上一题的解法,最后返回可能解的个数,也就是数组的容量大小.
这里,只需要返回可能解的个数, 所以不需要记录所有可能的解,仅仅需要一个可变的统计量count, 同时一个数组记录之前皇后的摆放位置, 这里使用pair结构来记录每个皇后的坐标(二维[x, y]). 具体代码如下:
Code
1 | class Solution { |