Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
和N-Queens 同样的解法。
class Solution {
public:
int totalNQueens(int n) {
vector<vector<string> > result;
vector<int> nums;
for(int i=0;i<n;i++)
nums.push_back(i);
vector<vector<int> > base=permutation(nums);
return base.size();
}
vector<vector<int> > permutation(vector<int> &nums)
{
vector<vector<int> >result;
permutationChild(nums,0,result);
return result;
}
void permutationChild(vector<int> &nums,int offset,vector<vector<int> >&result)
{
if(offset==nums.size()-1)
{
if(judge(nums))
result.push_back(nums);
return;
}
auto base=nums.begin()+offset;
auto iter=base;
for(;iter!=nums.end();iter++)
{
swap(*base,*iter);
permutationChild(nums,offset+1,result);
swap(*base,*iter);
}
}
bool judge(vector<int> & nums)
{
int length=nums.size();
for(int i=0;i<length;i++)
{
for(int j=i+1;j<length;j++)
{
if(abs(i-j)==abs(nums[i]-nums[j]))
return false;
}
}
return true;
}
};