## [Leetcode]52. N-Queens II(C++)

### 题目描述

The n-queens puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.

Given an integer `n`, return the number of distinct solutions to the n-queens puzzle.

### Constraints

• `1 <= n <= 9`

### 解题思路

``````#include <string>
#include <unordered_set>
#include <vector>

class Solution {
public:
int totalNQueens(int n) {
int result = 0;
std::unordered_set<int> col_used;
std::unordered_set<int> diag1;
std::unordered_set<int> diag2;
dfs(0, n, col_used, diag1, diag2, result);
return result;
}

private:
void dfs(int row, int n, std::unordered_set<int>& col_used,
std::unordered_set<int>& diag1, std::unordered_set<int>& diag2,
int& result) {
if (row == n) {
result++;
return;
}

std::string curr_row(n, '.');
for (int col = 0; col < n; ++col) {
if (col_used.count(col) || diag1.count(col - row) ||
diag2.count(col + row))
continue;
curr_row[col] = 'Q';
col_used.insert(col);
diag1.insert(col - row);
diag2.insert(col + row);
dfs(row + 1, n, col_used, diag1, diag2, result);
col_used.erase(col);
diag1.erase(col - row);
diag2.erase(col + row);
}
}
};
``````
• 时间复杂度: `O(n!)`
• 空间复杂度: `O(n)`

GitHub 代码同步地址： 52.NQueensIi.cpp

Built with Hugo
Theme Stack designed by Jimmy