#includemath.h class Solution { private : vector string solution; vector vector int result; vector int columns; public : bool check( int row, int col){ for ( int r= 0 ; rrow; r++ ) if (columns[r] == col || (row-r) == abs(columns[r]- col)) r
#include<math.h> class Solution { private: vector<string> solution; vector< vector <int>> result; vector<int> columns; public: bool check(int row, int col){ for(int r=0; r<row; r++) if(columns[r] == col || (row-r) == abs(columns[r]-col)) return false; return true; } void backtracking(int n, int row){ if(row == n){ result.push_back(columns); return; } for(int col=0; col<n; col++){ columns.push_back(col); if(check(row, col)) backtracking(n, row+1); columns.pop_back(); } } vector<vector<string>> solveNQueens(int n) { backtracking(n, 0); vector<vector<string>> res; for(auto &v:result){ vector<string> s; for(auto &c:v){ string t(n, ‘.‘); t[c] = ‘Q‘; s.push_back(t); } res.push_back(s); } return res; } };
解题方法借鉴https://leetcode-cn.com/problems/n-queens/solution/c-hui-su-fa-by-da-li-wang-4/