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

Leetcode: N-Queens II

2014-10-07 05:40 363 查看
Follow up for N-Queens problem.

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



Same as N-Queens. Use recursion within a loop. The result should be a static integer. 

public class Solution {
public static int sum;

public int totalNQueens(int n) {
if (n <= 0) {
return 0;
}

sum = 0;
ArrayList<Integer> cols = new ArrayList<Integer>();
helper(n, cols);
return sum;
}

private void helper(int n, ArrayList<Integer> cols) {
if (cols.size() == n) {
sum++;
return;
}

for (int i = 0; i < n; i++) {
if (isValid(cols, i)) {
cols.add(i);
helper(n, cols);
cols.remove(cols.size() - 1);
}
}
}

private boolean isValid(ArrayList<Integer> cols, int col) {
int row = cols.size();
for (int i = 0; i < row; i++) {
if (cols.get(i) == col || Math.abs(cols.get(i) - col) == Math.abs(i - row)) {
return false;
}
}

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