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

Leetcode: N-Queens II

2014-09-11 12:49 316 查看
Follow up for N-Queens problem.

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


跟N-Queen的考虑方式完全一样,NP问题,用循环递归处理子问题,具体做法就是:用循环去把皇后依次放在一行中的某列,如果这样放合法,然后就递归处理下一步,直到row=n说明 0到n-1行都已经处理完毕。这是得到一个合理的solution,把它加入result中

套路就是用一个循环去枚举当前所有情况,把元素加入,递归下一步,再把元素删除。

需要注意传值的问题,本题要传一个sum,如果直接定义一个integer来做sum,然后作为函数参数传入,递归之后再来检查sum的值,sum是不会有改变的,因为值传递,方法不会改变实参的值。所以用ArrayList<Integer>作为参数传入,这是一个对象,对象类型参数:传引用,方法体内改变形参引用,不会改变实参的引用,但有可能改变实参对象的属性值。

public class Solution {
public int totalNQueens(int n) {
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(0);
helper(n, 0, new int
, res);
return res.get(0);
}

public void helper(int n, int row, int[] ColForRow, ArrayList<Integer> res) {
if (row == n) { //find a suitable solution
res.set(0, res.get(0) + 1);
return;
}
for (int k = 0; k < n; k++) {
ColForRow[row] = k;
if (check(row, ColForRow)) {
helper(n, row+1, ColForRow, res);
}
}
}

public boolean check(int row, int[]ColForRow) {
for (int i = 0; i < row; i++) {
if (ColForRow[i] == ColForRow[row] || Math.abs(ColForRow[i] - ColForRow[row]) == Math.abs(i - row)) {
return false;
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: