class Solution {
private:
int res=0;
void backtrack(int row, vector& temp) {
if (row == temp.size()) {
res++;
return;
}
int n = temp[row].size();
for (int col = 0; col < n; col++) {
if (!vaild(temp, row, col)) {
continue;
}
temp[row][col] = ‘Q’;
backtrack(row + 1,temp);
temp[row][col] = ‘.’;
}
}
bool vaild(vector& temp, int row, int col) {
int n = temp.size();
for (int i = 0; i < n; i++) {
if (temp[i][col] == ‘Q’) {
return false;
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i–, j++) {
if (temp[i][j] == ‘Q’) {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i–, j–) {
if (temp[i][j] == ‘Q’) {
return false;
}
}
}
return true;
}
public:
int totalNQueens(int n) {
vectortemp(n, string(n, ‘.’));
if (n == 0)return res;
backtrack(0, temp);
return res;
}
};
这是我提交的正确的代码,我觉得下面这个样例不能通过