51. N-Queens

```class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > result;
if(n <= 0)
return result;
vector<int> queenCol(n,-1);
int curRow = 0;
solveNQueens(curRow,result,queenCol,n);
return result;
}

void solveNQueens(int curRow,vector<vector<string> >& result,vector<int>& queenCol,int n){
if(curRow == n){
vector<string> res(n,string(n,'.'));
for(int i = 0;i < n;i++)
res[i][queenCol[i]] = 'Q';
result.push_back(res);
return;
}
for(int i = 0;i < n;i++){
if(isValid(queenCol,curRow,i)){
queenCol[curRow] = i;
solveNQueens(curRow + 1,result,queenCol,n);
queenCol[curRow] = -1;
}
}
}

bool isValid(vector<int> queenCol,int row,int col){
for(int i = 0;i < row;i++){
if(queenCol[i] == col || abs(row - i) == abs(col - queenCol[i]))
return false;
}
return true;
}
}; ```

52. N-Queens II

result最终要作为返回值获得结果，所有的搜索情况都公用这个result，但是curRow，不同的搜索，搜索的值应该不一样

```class Solution {
public:
int totalNQueens(int n) {
if(n <= 0)
return 0;
vector<int> queenCol(n,-1);
int result = 0;
int curRow = 0;
totalNQueens(n,queenCol,result,curRow);
return result;
}
void totalNQueens(int n,vector<int>& queenCol,int& result,int curRow){
if(curRow == n){
result++;
return;
}
for(int i = 0;i < n;i++){
if(isValid(queenCol,curRow,i)){
queenCol[curRow] = i;
totalNQueens(n,queenCol,result,curRow+1);
queenCol[curRow] = -1;
}
}
}

bool isValid(vector<int>& queenCol,int row,int col){
for(int i = 0;i < row;i++){
if(queenCol[i] == col || abs(row - i) == abs(col - queenCol[i]))
return false;
}
return true;
}
};```

```class Solution {
public:
int totalNQueens(int n) {
if(n <= 0)
return 0;
vector<int> queenCol(n,-1);
int result = 0;
int curRow = 0;
totalNQueens(n,queenCol,result,curRow);
return result;
}
void totalNQueens(int n,vector<int> queenCol,int& result,int curRow){
if(curRow == n){
result++;
return;
}
for(int i = 0;i < n;i++){
if(isValid(queenCol,curRow,i)){
queenCol[curRow] = i;
totalNQueens(n,queenCol,result,curRow+1);
//queenCol[curRow] = -1;
}
}
}

bool isValid(vector<int>& queenCol,int row,int col){
for(int i = 0;i < row;i++){
if(queenCol[i] == col || abs(row - i) == abs(col - queenCol[i]))
return false;
}
return true;
}
};```