只要求返回所有的方案数 (详细题解见 上一题 LC51. N 皇后(dfs ))
class Solution {
public:
int n;
vector<vector<string>> ans;
vector<string> path;
vector<bool> col, dg, udg;
int totalNQueens(int _n) {
n = _n;
col = vector<bool>(n);
dg = udg = vector<bool>(2 * n);
path = vector<string>(n, string(n, '.'));
dfs(0);
return ans.size(); //直接返回上一题的ans.size()就可以了
}
void dfs(int u) {
if (u == n) {
ans.push_back(path);
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;
path[u][i] = 'Q';
dfs(u + 1);
path[u][i] = '.';
col[i] = dg[u - i + n] = udg[u + i] = false;
}
}
}
};
class Solution {
public:
int n;
vector<bool> col, dg, udg;
int totalNQueens(int _n) {
n = _n;
col = vector<bool>(n);
dg = udg = vector<bool>(2 * n);
return dfs(0); //直接返回上一题的ans.size()就可以了
}
int dfs(int u) {
if (u == n) return 1;
int res = 0;
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;
res += dfs(u + 1);
col[i] = dg[u - i + n] = udg[u + i] = false;
}
}
return res;
}
};