52. N-Queens II

原创 2016年08月30日 10:53:48

Follow up for N-Queens problem.

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

public class Solution {
    static int[] col;	
	static int count;

	public static void main(String[] args) {
		System.out.print(totalNQueens(2));

	}

	public static int totalNQueens(int n) {	
		col = new int[n];
		count = 0;
		nqueens(0, n);
		return count;
	}

	public static void nqueens(int colIndex, int n) {
		if (colIndex == n) {
			count++;
			return;
		}
		for (int i = 0; i < n; i++) {
			col[colIndex] = i;
			if (valid(colIndex)) {
				nqueens(colIndex + 1, n);
			}
		}
	}

	private static boolean valid(int colIndex) {
		for (int i = 0; i < colIndex; i++) {
			// 行不可能重复,列如果重复或者对角线重复
			if (col[i] == col[colIndex]
					|| Math.abs(col[i] - col[colIndex]) == colIndex - i) {
				return false;
			}
		}
		return true;
	}

}



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode52——N-Queens II

LeetCode52——N-Queens II 跟LeetCode51一样,只不过这题是求解解的个数。 这里我套用了上一题的代码,只不过当row==n(递归返回条件)时,不是将一种可行解加入结果集...

[leetcode] 52.N-Queens II

题目:Follow up for N-Queens problem.Now, instead outputting board configurations, return the total num...

LeetCode 52. N-Queens II 解题报告

LeetCode 52. N-Queens II 解题报告

LeetCode | 52.N-Queens II

类似上一篇博客N皇后,但是由于这里的N会特别大(10^9),所以不能直接用数组,内存会爆掉.可以用动态数组vector每次push_back. 3ms AC.class Solution { pub...

LeetCode 52. N-Queens II 题解(C++)

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numb...

LeetCode 52. N-Queens II(N皇后)

原题网址:https://leetcode.com/problems/n-queens-ii/ Follow up for N-Queens problem. Now, instead...

leetcode-52. N-Queens II

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total nu...

LeetCode_52---N-Queens II

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numb...

Leetcode 52. N-Queens II (Hard) (cpp)

Leetcode 52. N-Queens II (Hard) (cpp)

LeetCode52 N-Queens II

详细见:leetcode.com/problems/n-queens-ii Java Solution: github package leetcode; public class ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)