您的位置:首页 > 产品设计 > UI/UE

【LeetCode】52. N-Queens II

2014-12-12 10:46 375 查看
N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.



简单的回溯法。

cur[i] == j 代表第i行的皇后位于第j列。

对于每一行,尝试所有列,

如果当前行尝试的位置不与前面所有行的位置冲突,则可以递归到下一行。

class Solution {
public:
int totalNQueens(int n) {
int count = 0;
vector<int> cur;
Helper(count, cur, 0, n);
return count;
}
void Helper(int& count, vector<int> cur, int pos, int n)
{
if(pos == n)
count ++;
else
{
for(int i = 0; i < n; i ++)
{
cur.push_back(i);
if(check(cur))
Helper(count, cur, pos+1, n);
cur.pop_back();
}
}
}
bool check(vector<int> cur)
{
int size = cur.size();
int loc = cur[size-1];
for(int i = 0; i < size-1; i ++)
{
//never same row

//col
if(cur[i] == loc)
return false;

//diag
if(abs(cur[i]-loc) == abs(i-size+1))
return false;
}
return true;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: