Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
这道题和第51题基本没有太大区别,题目难度为Hard。
如果需要详细解释请看第51题(传送门),具体代码:
class Solution {
public:
int totalNQueens(int n) {
vector<string> curRst(n, string(n, '.'));
int cnt = 0;
NQueens(curRst, 0, n, cnt);
return cnt;
}
void NQueens(vector<string> &curRst, int row, int n, int &cnt) {
if(row == n) {
cnt++;
return;
}
for(int i=0; i<n; i++) {
bool flag = true;
for(int j=0; j<row; j++) {
if(curRst[j][i] == 'Q') {
flag = false;
break;
}
if((i+j-row >= 0) && (i+j-row <= n-1) && (curRst[j][i+j-row] == 'Q')) {
flag = false;
break;
}
if((i+row-j >= 0) && (i+row-j <= n-1) && (curRst[j][i+row-j] == 'Q')) {
flag = false;
break;
}
}
if(flag) {
curRst[row++][i] = 'Q';
NQueens(curRst, row, n, cnt);
curRst[--row][i] = '.';
}
}
}
};