-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0052-n-queens-ii.java
38 lines (35 loc) · 1.1 KB
/
0052-n-queens-ii.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
int count = 0;
public int totalNQueens(int n) {
Set<Integer> colSet = new HashSet<>();
Set<Integer> posDiagSet = new HashSet<>(); // (r + c)
Set<Integer> negDiagSet = new HashSet<>(); // (r - c)
backtrack(0, n, colSet, posDiagSet, negDiagSet);
return count;
}
private void backtrack(
int row,
int n,
Set<Integer> colSet,
Set<Integer> posDiagSet,
Set<Integer> negDiagSet) {
if (row == n) {
count += 1;
return;
}
for (int col = 0; col < n; col++) {
if (colSet.contains(col)
|| posDiagSet.contains(row + col)
|| negDiagSet.contains(row - col)) {
continue;
}
colSet.add(col);
posDiagSet.add(row + col);
negDiagSet.add(row - col);
backtrack(row + 1, n, colSet, posDiagSet, negDiagSet);
colSet.remove(col);
posDiagSet.remove(row + col);
negDiagSet.remove(row - col);
}
}
}