代码
class Solution {
public:
vector<bool> col, dg, udg;
int ans, N;
int totalNQueens(int n) {
N = n;
col = vector<bool>(N);
dg = udg = vector<bool>(N * 2);
dfs(0);
return ans;
}
void dfs(int u) {
if (u == N) {
ans++;
return;
}
for (int i = 0; i < N; ++i) {
if (!col[i] && !dg[u - i + N] && !udg[u + i]) {
col[i] = dg[u - i + N] = udg[u + i] = true;
dfs(u + 1);
col[i] = dg[u - i + N] = udg[u + i] = false;
}
}
}
};