dfs + backtracing 典型题目ip
须要注意的地方:
1.剪枝放在了下行状态的循环内部
2.须要判别当前位置能否放置皇后,当前列,两条对角线都是须要考虑的ci
class Solution { public: bool setable(const vector<string> &cur, const vector<int> & col_used, int row,int col, int n) { if (col_used[col] == 1) return false; int i = row - 1; int j = col - 1; while (i >= 0 && j >= 0) { if (cur[i][j] == 'Q') return false; --i; --j; } i = row - 1; j = col + 1; while (i >= 0 && j < n) { if (cur[i][j] == 'Q') return false; --i; ++j; } return true; } void dfs(vector<vector<string>> &vct, vector<string> &cur, vector<int> & col_used, int row, int n) { if (row >= n) { vct.push_back(cur); return; } for (int i = 0; i<n; ++i) { // try to set queen at a[row][i]; if (setable(cur, col_used, row, i,n)) { col_used[i] = 1; cur[row][i] = 'Q'; dfs(vct, cur, col_used, row + 1, n); cur[row][i] = '.'; col_used[i] = 0; } } } vector<vector<string>> solveNQueens(int n) { vector<vector<string>> vct; if (n <= 0) return vct; vector<string> cur(n, string(n, '.')); vector<int> col_used(n, 0); dfs(vct, cur, col_used, 0, n); return vct; } };
Leetcode - 052. N-Queens IIleetcode
惟一不一样的地方在于:不须要存储最终的放置方案,只须要统计方案的个数,因此将全部vct替换为int ans,vct.push_back(cur) 替换为 ++ans ,最后将ans返回便可(只有返回值表明的含义不一样,固然如果偷懒的话返回vct.size() 也不是不能够)get