My code:
public class Solution {
private int counter = 0;
public int totalNQueens(int n) {
if (n <= 0) {
return 0;
}
helper(0, new boolean[n], new boolean[2 * n], new boolean[2 * n], n);
return counter;
}
private void helper(int row, boolean[] col, boolean[] l1, boolean[] l2, int n) {
if (row >= n) {
counter++;
return;
}
for (int i = 0; i < n; i++) {
int index1 = row - i + n;
int index2 = 2 * n - i - row - 1;
if (!col[i] && !l1[index1] && !l2[index2]) {
col[i] = true;
l1[index1] = true;
l2[index2] = true;
helper(row + 1, col, l1, l2, n);
col[i] = false;
l1[index1] = false;
l2[index2] = false;
}
}
}
}
就把 I 改了下,就交了。思路差不多。
核心就是,那两条对称斜线,是可以各用一个数字来表示的。
Anyway, Good luck, Richardo! -- 09/23/2016
网友评论