码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] N-Queens II

时间:2014-06-27 11:40:13      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:class   code   java   http   tar   com   

Follow up for N-Queens problem.

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

https://oj.leetcode.com/problems/n-queens-ii/

思路:参考N-Queens,只统计个数即可。

 

public class Solution {
	public int totalNQueens(int n) {
		if (n <= 0)
			return 0;
		int[] perm = new int[n];
		slove(perm, 0, n);

		return count;
	}

	private int count = 0;

	private void slove(int[] perm, int cur, int n) {
		if (cur == n) {
			count++;
		} else {
			int i;
			for (i = 0; i < n; i++) {
				int j;
				boolean ok = true;
				for (j = 0; j < cur; j++) {
					if (perm[j] == i || perm[j] - j == i - cur
							|| perm[j] + j == i + cur)
						ok = false;
				}
				if (ok) {
					perm[cur] = i;
					slove(perm, cur + 1, n);
				}

			}

		}

	}

	public static void main(String[] args) {
		System.out.println(new Solution().totalNQueens(8));

	}
}

 

 

[leetcode] N-Queens II,布布扣,bubuko.com

[leetcode] N-Queens II

标签:class   code   java   http   tar   com   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!