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

[leetcode]N-Queens II

2014-06-17 20:36 337 查看


N-Queens II

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.



解题思路:回溯法
class Solution {
public:
bool place(int *x, int t){
for(int i = 0; i < t; i++){
if(abs(t - i) == abs(x[t] - x[i]) || x[t] == x[i]) return false;
}
return true;
}

void backTrace(int *x, int n, int t, int &sum){
if(t >= n){
sum++;
return;
}
for(int i = 0; i < n; i++){
x[t] = i;
if(place(x, t)){
backTrace(x, n, t + 1, sum);
}
}
}

int totalNQueens(int n) {
int *x = new int
();
int sum = 0;

backTrace(x, n, 0, sum);
delete x;

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