class Solution {
public:
int totalNQueens(int n) {
vector<int> col;
int cnt = 0;
solveNQ(n, col, 0, cnt);
return cnt;
}
private:
void solveNQ(int n, vector<int>& col, int newRow, int & cnt) {
if (newRow == n) {
++cnt;
return;
}
for (int i = 0; i < n; i++) {
if (isValid(col, i, newRow)) {
col.push_back(i);
solveNQ(n, col, newRow + 1, cnt);
col.pop_back();
}
}
}
bool isValid(vector<int>& col, int newCol, int newRow){
for (int i = 0; i < col.size(); i++) {
if (newCol == col[i] ||
abs(newCol - col[i]) == abs(newRow - i)) {
return false;
}
}
return true;
}
};