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

LeetCode | N-Queens II

2014-08-21 11:35 274 查看
Follow up for N-Queens problem.

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



题目解析:

这次是统计个数,利用上一题的方案二,将最后的构造二维数组改成count计数就行了。

class Solution {
public:
bool check(int row, int* place)
{
for (int i = 0; i < row; ++i)
{
int diff = abs(place[i] - place[row]);
if (diff == 0 || diff == row - i)
return false;
}
return true;
}

void placeQueens(int row, int n, int &count, int* place)
{
if (row == n)
{
++count;
return;
}

for (int i = 0; i < n; ++i)
{
place[row] = i;
if (check(row, place))
placeQueens(row+1, n, count, place);
}
}

int totalNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int* place = new int
;
int count = 0;
placeQueens(0, n, count, place);
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: