52. N-Queens II
52的解法相对比51更简单,无需保存具体的结果,只是统计符合条件解法的个数。代码从51的解法稍加修改:

class Solution {
public:
    int totalNQueens(int n) {
        vector<string> nQueens(n,string(n,'.'));
        int cnt = 0;
        solveNQueens(nQueens,0,n,cnt);
        
        return cnt;
        
    }
private:
    void solveNQueens(vector<string> &nQueens, int row, int n,int & cnt) {
        if(row == n){
            //找到一个符合条件的解法
            cnt += 1;
            return;
        }
        
        for(int col = 0;col < n;col++){
            if(checksafe(nQueens,row,col,n)){
                nQueens[row][col]='Q';
                solveNQueens(nQueens,row + 1,n,cnt);
                nQueens[row][col]='.';
            }
        }
    }
    
    bool checksafe(vector<string> &nQueens,int row,int col,int n){
        //判断当前列是否有皇后
        for(int i = 0;i < row;i++){
            if(nQueens[i][col] == 'Q'){
                return false;
            }
        }
        //判断左上45度是否已有皇后
        for(int i = row - 1,j = col - 1;i >= 0 && j >= 0;i--,j--){
          if(nQueens[i][j] == 'Q'){
              return false;
          }  
        }
        
        //判断右上45度是否已有皇后
        for(int i = row - 1,j = col + 1;i >= 0 && j < n;i--,j++){
          if(nQueens[i][j] == 'Q'){
              return false;
          }  
        }
        
        return true;
    }
};