题目:52. N皇后 II
思路:回溯。
不需要打印棋盘,所以只需要一个变量记录找到的解即可。
代码:
class Solution {
public int res = 0;
public int totalNQueens(int n) {
int[] queen = new int[n];
Arrays.fill(queen, -1);
backtrack(queen, 0, n);
return res;
}
public void backtrack(int[] queen, int cur, int n) {
if (cur == n) {
res ++;
return;
}
for (int i = 0; i < n; i ++) {
if (canPlace(queen, cur, i)) {
queen[cur] = i;
backtrack(queen, cur + 1, n);
queen[cur] = -1;
}
}
}
public boolean canPlace(int[] queen, int index, int k) {
for (int i = 0; i < index; i++) {
if (queen[i] == k || Math.abs(index - i) == Math.abs(k - queen[i])) {
return false;
}
}
return true;
}
}