任然是NP问题,解决此类问题主要思想就是递归,
就是用一个循环去枚举当前所有情况,然后把元素加入,递归,再把元素移除
代码1 提示 Output Limit Exceeded 输出结果中有重复的
class Solution {
public:
void solveNQueensHelper(vector<vector<string> > &result, vector<string> &tempResult, vector<bool> &flagRow, vector<bool> &flagCol, int &num, int n)
{
if(num==n)
{
result.push_back(tempResult);
return ;
}
for(int i = 0; i < n; ++i)
{
if(flagRow[i]==false)
continue;
for(int j = 0; j < n; ++j)
{
if(flagCol[j]==false)
continue;
tempResult[i][j] = 'Q';
flagRow[i] = false;
flagCol[j] = false;
num++;
solveNQueensHelper(result, tempResult, flagRow, flagCol, num, n);
num--;
flagRow[i] = true;
flagCol[j] = true;
tempResult[i][j] = '.';
}
}
return ;
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > result;
if(n==0)
return result;
vector<bool> flagRow(n, true);
vector<bool> flagCol(n, true);
vector<string> tempResult;
for(int i = 0; i < n; ++i)
{
string str = "";
for(int j = 0; j < n; ++j)
str += '.';
tempResult.push_back(str);
}
int num = 0;
solveNQueensHelper(result, tempResult, flagRow, flagCol, num, n);
return result;
}
};
Accepted 代码 参考 http://www.cnblogs.com/TenosDoIt/p/3801621.html
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > result;
if(n==0)
return result;
vector<int> state(n,-1);
solveNQueensHelper(result, state, 0);
return result;
}
void solveNQueensHelper(vector<vector<string> > &result, vector<int> &state, int row)
{
int n = state.size();
if(row==n)
{
vector<string> temp(n, string(n, '.'));
for(int i = 0; i < n; ++i)
{
temp[i][state[i]] = 'Q';
}
result.push_back(temp);
return ;
}
for(int col = 0; col < n; ++col)
{
if(isValid(state, row, col))
{
state[row] = col;
solveNQueensHelper(result, state, row+1);
state[row] = -1;
}
}
return ;
}
bool isValid(vector<int> &state, int row, int col)
{
for(int i = 0; i < row; ++i)
if(state[i]==col || abs(row - i) == abs(col - state[i]))
return false;
return true;
}
};