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

LeetCode - N-Queens II

2014-02-13 20:22 218 查看
N-Queens II

2014.2.13 20:01

Follow up for N-Queens problem.

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



Solution:

  This problem is a simplification from the N-Queens. This time we only have record the number of solutions.

  Time complexity is O(n!). Space complexity is O(n!) as well, which comes from parameters in recursive function calls.

Accepted code:

// 3CE, 1AC, why so hasty?
class Solution {
public:
int totalNQueens(int n) {
a = nullptr;
if (n <= 0) {
return 0;
}

res_count = 0;
a = new int
;
solveNQueensRecursive(0, a, n);
delete[] a;

return res_count;
}
private:
int *a;
int res_count;

void solveNQueensRecursive(int idx, int a[], const int &n) {
if (idx == n) {
// one solution is found
++res_count;
return;
}

int i, j;
// check if the current layout is valid.
for (i = 0; i < n; ++i) {
a[idx] = i;
for (j = 0; j < idx; ++j) {
if (a[j] == a[idx] || myabs(idx - j) == myabs(a[idx] - a[j])) {
break;
}
}
if (j == idx) {
// valid layout.
solveNQueensRecursive(idx + 1, a, n);
}
}
}

int myabs(const int x) {
return (x >= 0 ? x : -x);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: