思路:和上一道题类似。只需要在没生成一种解法时,不需要输出具体的解,而是将计数器+1即可。
class Solution {
public:
bool isValue(vector<int>&pos,int row,int col)
{
for(int i=0;i<row;++i)
{
if(col==pos[i]||abs(row-i)==abs(col-pos[i])) return false;
}
return true;
}
void totalNQueenDFS(vector<int>&pos,int row,int &ans)
{
int n=pos.size();
if(row==n) ++ans;
else
{
for(int col=0;col<n;++col)
{
if(isValue(pos,row,col))
{
pos[row]=col;
totalNQueenDFS(pos,row+1,ans);
pos[row]=-1;
}
}
}
}
int totalNQueens(int n) {
int ans=0;
vector<int> pos(n,-1);
totalNQueenDFS(pos,0,ans);
return ans;
}
};