https://leetcode.com/problems/n-queens/
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
if (n <= 0){
return res;
}
vector<int> sol(n);
helper(n, sol, 0);
return res;
}
void helper(int n,vector<int>& sol, int cur){
if (cur == n){
vector<string> vec;
for (int i = 0; i < n; i++){
string str = "";
for (int j = 0; j < n; j++){
if (j != sol[i]){
str.append(".");
}
else{
str.append("Q");
}
}
vec.push_back(str);
}
res.push_back(vec);
return;
}
for (int col = 0; col < n; col++){
bool flag = true;
for (int i = 0; i < cur; i++){
if (sol[i] == col || sol[i] - i == col - cur || sol[i] + i == col + cur){
flag = false;
break;
}
}
if (flag){
sol[cur] = col;
helper(n, sol, cur + 1);
}
}
}
private:
vector<vector<string> >res;
};