思路:
DFS
map[row] = col
表示第row
行的皇后放置在col
列上。
与上一题相同,直接求出解的个数即可。不必记录所有的解。
时间复杂度O(N!),空间复杂度O(N)。
class Solution {
public:
bool canSet(vector<int> &map, int n, int row, int col) {
for(int prow = 0; prow < row; ++prow) {
int pcol = map[prow];
if(pcol == col) return false;
if( (prow - row) == (pcol - col) ) return false;
if( (row - prow) == (pcol - col) ) return false;
}
return true;
}
void dfs(vector<int> &map, int n, int row, int &ans) {
if(row == n) {
ans++;
return;
}
for(int col = 0; col < n; ++col) {
if(canSet(map, n, row, col)) {
map[row] = col;
dfs(map, n, row + 1, ans);
map[row] = 0;
}
}
}
int totalNQueens(int n) {
int ans = 0;
vector<int> map = vector<int>(n, 0);
dfs(map, n, 0, ans);
return ans;
}
};