赞
踩
https://programmercarl.com/0051.N%E7%9A%87%E5%90%8E.html
代码随想录讲的很清楚。
back_tracking(chessboard, row + 1)
其参数为row+1i==n
class Solution { public: // vector<string> path_; vector<vector<string>> res_; bool valid(vector<string>& chessboard, int row, int col) { for (int j = 0; j < row; j++) { if (chessboard[j][col] == 'Q') { return false; } } for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (chessboard[i][j] == 'Q') { return false; } } for (int i = row, j = col; i >= 0 && j < chessboard.size(); i--, j++) { if (chessboard[i][j] == 'Q') { return false; } } return true; } void back_tracking(vector<string> chessboard, int row) { if (row == chessboard.size()) { res_.push_back(chessboard); return; } // for (int i = row; i < chessboard.size(); i++) { for (int j = 0; j < chessboard[0].size(); j++) { if (valid(chessboard, row, j)) { chessboard[row][j] = 'Q'; back_tracking(chessboard, row + 1); chessboard[row][j] = '.'; } } // } } vector<vector<string>> solveNQueens(int n) { vector<string> chessboard(n, string(n, '.')); back_tracking(chessboard, 0); return res_; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。