Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

与N-Queens I 完全相同, 只是返回的是个数
ublic class Solution {
public int totalNQueens(int n) {
int[] res = new int[1];
if (n <= 0) {
return res[0];
}
int[] column = new int[n];
helper(res, column, n, 0);
return res[0];
}
public void helper(int[] res, int[] column, int n, int pos) {
if (pos == n) {
res[0]++;
} else {
for (int i = 0; i < n; i++) {
column[pos] = i;
if (isValid(column, pos)) {
helper(res,column, n, pos + 1);
}
}
}
}
public boolean isValid(int[] column, int pos) {
for (int i = 0; i < pos; i++) {
if (column[i] == column[pos] || Math.abs(column[i] - column[pos]) == pos - i) {
return false;
}
}
return true;
}
}
没有评论:
发表评论