首页 > 代码库 > [leetcode] N-Queens II
[leetcode] N-Queens II
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)); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。