52.N-Queens II
N-Queens II Total Accepted: 24073 Total Submissions: 68213 Question Solution
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Hide Tags Have you met this question in a real interview? Yes No
思路:跟上一题没啥区别。回溯法
class Solution { public:
void _backtrack(int &res,vector<int> &tem_one_res,int n,int t){
if(t>=n){
++res;
return;
} else{
for(int j=0;j<n;++j){
bool attack_flag=false;
for(int i=0;i<t;++i){
if(tem_one_res[i]==j || abs(tem_one_res[i]-j)==(t-i)){
attack_flag=true;
break;
}
}
if(!attack_flag){
tem_one_res.push_back(j);
_backtrack(res,tem_one_res,n,t+1);
tem_one_res.pop_back();
}
}
}
}
int totalNQueens(int n) {
if(n<1) return 0;
int res=0;
vector<int> one_res;
_backtrack(res,one_res,n,0);
return res;
}
};