[LeetCode 52] N-Queens II
这一题就是上一题的简化版了,我们只针对上面的算法2来求解这一题
class Solution {
public:
int totalNQueens(int n) {
vector
//判断在row行col列位置放一个皇后,是否是合法的状态
//已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
bool isValid(vector<int> &state, int row, int col){
for(int i = 0; i < row; i++)//只需要判断row前面的行,因为后面的行还没有放置
if(state[i] == col || abs(row - i) == abs(col - state[i]))
return false;
return true;
}
private: int res; };
class Solution {
public:
int totalNQueens(int n) {
vector
void solveNQ(int n, int irow, vector<int> &col, int &totSol) {
if(irow == n) {
totSol++;
return;
}
for(int icol = 0; icol < n; ++icol) {
if(validPos(col, irow, icol)) {
col.push_back(icol);
solveNQ(n, irow + 1, col, totSol);
col.pop_back();
}
}
}
bool validPos(vector<int> &col, int irow, int icol) {
if(irow < col.size()) return false;
for(int i = 0; i < col.size(); i++) {
if(icol == col[i] || abs(irow - i) == abs(icol - col[i]))
return false;
}
return true;
}
};