這就是傳說中的N皇后? 回溯算法安排!| LeetCode:51.N皇后

按順序看下來,到這里能自己做出來了!貼一個c++
class Solution {
public:
? ? vector<vector<string>> res;
? ? vector<vector<int>> pos;
? ? int n;
? ? string s="";
? ? void draw(){
? ? ? ? vector<string> t_res(n, s);
? ? ? ? for (auto p: pos){
? ? ? ? ? ? t_res[p[0]][p[1]] = 'Q';
? ? ? ? }
? ? ? ? res.push_back(t_res);
? ? }
? ? bool is_legal(int x, int y){
? ? ? ? int dx, dy;
? ? ? ? for (auto p: pos){
? ? ? ? ? ? dx = abs(x-p[0]), dy = abs(y-p[1]);
? ? ? ? ? ? if (dx == 0 || dy == 0 || dx == dy) {
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return true;
? ? }
? ? void backtracking(int idx){
? ? ? ? if (pos.size() == n){
? ? ? ? ? ? draw();
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? for (int i=idx; i<n; ++i){
? ? ? ? ? ? for (int j=0; j<n; ++j){
? ? ? ? ? ? ? ? if (is_legal(i, j)){
? ? ? ? ? ? ? ? ? ? pos.push_back({i, j});
? ? ? ? ? ? ? ? ? ? backtracking(i+1);
? ? ? ? ? ? ? ? ? ? pos.pop_back();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if (pos.size()-1 != i) break;
? ? ? ? }
? ? }
? ? vector<vector<string>> solveNQueens(int n) {
? ? ? ? this->n = n;
? ? ? ? for (int i=0; i<n; ++i) s+='.';
? ? ? ? backtracking(0);
? ? ? ? return res;
? ? }
};