使用全排列的方法做的,效率超低的,104ms.
class Solution {
public:
bool CheckNQueuesOK(const vector<int>& queen)
{
int len = queen.size();
for(int i = 0;i<len;i++)
{
for(int j = i+1;j<len;j++)
{
if(queen[i] - queen[j] == i -j || queen[j] - queen[i] == i - j)
return false;
}
}
return true;
}
vector<string> ChangeQueenInt2String(const vector<int>& queen)
{
vector<string> q;
for(int i = 0;i<queen.size();i++)
{
//设置第i行中的queen[i]为‘Q’,其他均为.
string tmp;
for(int j = 0;j<queen.size();j++)
{
if(queen[i] == j)
tmp += 'Q';
else
tmp += '.';
}
q.push_back(tmp);
}
return q;
}
void Permutation(vector<int>& queen, int start, vector<vector<string>>& AllQueens)
{
if(start == queen.size())
{
if(CheckNQueuesOK(queen))
{
//save
vector<string> q = ChangeQueenInt2String(queen);
AllQueens.push_back(q);
}
}
for(int i = start; i < queen.size();i++)
{
//swap
int tmp = queen[i];
queen[i] = queen[start];
queen[start] = tmp;
Permutation(queen, start+1, AllQueens);
tmp = queen[i];
queen[i] = queen[start];
queen[start] = tmp;
}
}
vector<vector<string>> solveNQueens(int n) {
vector<int> queue;
//初始化
for(int i = 0;i<n;i++)
queue.push_back(i);
vector<vector<string>> q;
Permutation(queue, 0, q);
return q;
}
};