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

【LeetCode】N-Queens II N皇后问题 回溯法

2014-03-15 20:46 561 查看

N-Queens II

Total Accepted: 4852
Total Submissions: 16065

Follow up for N-Queens problem.

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



Have you been asked this question in an interview?

class Solution {
public:

int sum;
int *board;

bool isok(int k) //check whether the kth Queen can be put down.
{
for(int i = 1; i < k; i++)
{
if(board[i] == board[k] || abs(i-k) == abs(board[i] - board[k]))
return false;
}
return true;
}

void totalN(int n, int k)
{
if(k > n)
sum++;
else{
for(int i = 1; i <= n; i++)
{
board[k] = i;
if(isok(k))
totalN(n, k+1);
}
}
}

int totalNQueens(int n) {
board = new int[n+1];
sum = 0;
totalN(n, 1);
int res = sum;
delete []board;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: