使用全排列的思路,效率很低。
class Solution {
public:
bool QueenOrderOK(const vector<int>& q)
{
for(int i = 0 ;i<q.size();i++)
{
for(int j = i+1;j<q.size();j++)
{
if(i - j == q[i] - q[j] || j - i == q[i] - q[j])
return false;
}
}
return true;
}
void GetAllQueens(vector<int>& q, int start, int& QueensNum)
{
if(start == q.size())
{
//check
if(QueenOrderOK(q))
QueensNum++;
}
for(int i = start; i < q.size();i++)
{
//swap i & start
int tmp = q[i];
q[i] = q[start];
q[start] = tmp;
GetAllQueens(q, start+1, QueensNum);
tmp = q[i];
q[i] = q[start];
q[start] = tmp;
}
}
int totalNQueens(int n) {
vector<int> q;
q.resize(n);
for(int i = 0;i<n;i++)
q[i] = i;
int num = 0;
GetAllQueens(q, 0, num);
return num;
}
};