N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
解题思路:回溯法
class Solution {
public:
bool place(int *x, int t){
for(int i = 0; i < t; i++){
if(abs(t - i) == abs(x[t] - x[i]) || x[t] == x[i]) return false;
}
return true;
}
void backTrace(int *x, int n, int t, int &sum){
if(t >= n){
sum++;
return;
}
for(int i = 0; i < n; i++){
x[t] = i;
if(place(x, t)){
backTrace(x, n, t + 1, sum);
}
}
}
int totalNQueens(int n) {
int *x = new int[n]();
int sum = 0;
backTrace(x, n, 0, sum);
delete x;
return sum;
}
};