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

public class Solution {
private int num = 0;
public int totalNQueens(int n) {
solve(0, n, new int[n]);
return num;
}
private void solve(int i, int n, int[] positions) {
if (i == n) {
num++;
} else {
for (int j = 0; j < n; j++) {
positions[i] = j;
if (validate(i, positions)) {
solve(i+1, n, positions);
}
}
}
}
private boolean validate(int maxRow, int[] positions) {
for (int i = 0; i < maxRow; i++) {
if (positions[i] == positions[maxRow]
|| Math.abs(positions[i] - positions[maxRow]) == maxRow - i)
return false;
}
return true;
}
}
312

被折叠的 条评论
为什么被折叠?



