题目:
The n-queens puzzle is the problem of placing n queens on an n×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.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
代码:
class Solution {
private:
vector<vector<string> > res;
public:
bool isValid(vector<string> v, int row, int col) {
//列
for (int i = 0; i < row; i++) {
if (v[i][col] == 'Q')return false;
}
//右对角线
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (v[i][j] == 'Q')return false;
}
//左对角线
for (int i = row - 1, j = col + 1; i >= 0 && j < v.size(); i--, j++) {
if (v[i][j] == 'Q')return false;
}
return true;
}
void iterate(vector<string>& v, int row) {
if (row == v.size()) {
res.push_back(v);
}
for (int i = 0; i < v.size(); i++) {
if (isValid(v, row, i)) {
v[row][i] = 'Q';
iterate(v, row + 1);
v[row][i] = '.';
}
}
}
int totalNQueens(int n) {
vector<string> v(n, string(n, '.'));
iterate(v, 0);
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
int len = res.size();
return len;
}
};
思路:
一行一行遍历,写递归,加了引用以后会变得更快