Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1925117

Browse files
committed
Add solution #52
1 parent b5cfbd2 commit 1925117

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

0052-n-queens-ii.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 52. N-Queens II
3+
* https://leetcode.com/problems/n-queens-ii/
4+
* Difficulty: Hard
5+
*
6+
* The n-queens puzzle is the problem of placing n queens on an n x n
7+
* chessboard such that no two queens attack each other.
8+
*
9+
* Given an integer n, return the number of distinct solutions to the
10+
* n-queens puzzle.
11+
*/
12+
13+
/**
14+
* @param {number} n
15+
* @return {number}
16+
*/
17+
var totalNQueens = function(n) {
18+
const result = [];
19+
backtrack(result, n);
20+
return result.length;
21+
};
22+
23+
function backtrack(result, n, board = [], size = 0) {
24+
if (n === size) {
25+
result.push(board.map(s => `${'.'.repeat(s)}Q${'.'.repeat(n - s - 1)}`));
26+
} else {
27+
for (let rows = 0; rows < n; rows++) {
28+
const isValid = !board.some((i, j) => {
29+
return i === rows || i === rows + size - j || i === rows - size + j;
30+
});
31+
if (isValid) {
32+
board.push(rows);
33+
backtrack(result, n, board, size + 1);
34+
board.pop();
35+
}
36+
}
37+
}
38+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
49|[Group Anagrams](./0049-group-anagrams.js)|Medium|
5858
50|[Pow(x, n)](./0050-powx-n.js)|Medium|
5959
51|[N-Queens](./0051-n-queens.js)|Hard|
60+
52|[N-Queens II](./0052-n-queens-ii.js)|Hard|
6061
53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy|
6162
54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium|
6263
57|[Insert Interval](./0057-insert-interval.js)|Medium|

0 commit comments

Comments
 (0)