Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Code:
<span style="font-size:14px;">class Solution {
public:
void helper(vector<int> &positions, const int &n, int index, int &result) {
if (index == n) {
++result;
return;
}
for (int i = 0; i < n; ++i) {
bool invalid = false;
for (int j = 0; j < index; ++j)
if (positions[j] == i || abs(positions[j]-i) == abs(j-index)) {
invalid = true;
break;
}
if (!invalid) {
positions[index] = i;
helper(positions, n, index+1, result);
}
}
}
int totalNQueens(int n) {
if (n == 0 || n == 1) return n;
int result = 0;
vector<int> positions(n, -1);
helper(positions, n, 0, result);
return result;
}
};</span>