8.18 [LeetCode 52] N-Queens II

[LeetCode 52] N-Queens II

COMMENTS

Question

link

Follow up for N-Queens problem.

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

Stats

Frequency 3
Difficulty 4
Adjusted Difficulty 2
Time to use ——–

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Solution

I posted 2 solution by me. Second code is same as this guy’s code.

My code

Using global variable (similar to [LeetCode 51] N-Queens)

 1 public class Solution {
 2     int res = 0; // res should be global, cause java func cannot return int value back.
 3     public int totalNQueens(int n) {
 4         //int res = 0;
 5         //int[] col4row = new int[n];
 6         helper(n, 0, new int[n]);
 7         return res;
 8     }
 9
10     private void helper(int n, int row, int[] col4row) {
11         if(row == n) { // all positions are ok
12             ++res;
13             return; // do not forget to quit from this recursion here.
14         }
15         for(int i = 0; i < n; i++) {
16             col4row[row] = i; // put every col to this row to test the correctness.
17             if(check(row, col4row)) {
18                 helper(n, row+1, col4row);
19             }
20         }
21     }
22
23     private boolean check(int row, int[] col4row) {
24         for(int i = 0; i < row; i++) {
25             if(col4row[i] == col4row[row] ||
26                 Math.abs(col4row[i]-col4row[row]) == row-i)
27                 return false;
28         }
29         return true;
30     }
31 }

Without using global variable,

public class Solution {
    public int totalNQueens(int n) {
        return solve(0, n, new int[n]);
    }

    private int solve(int row, int n, int[] col4row) {
        if (row == n) return 1;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            boolean conflict = false;
            for (int j = 0; j < row; j++) // check first, if not ok then go to next col, if ok let col4row[row] = i;
                if (i == col4row[j] || row - j == Math.abs(i - col4row[j]))
                    conflict = true;
            if (conflict) continue;
            col4row[row] = i;
            ans += solve(row + 1, n, col4row); // this row is finished, go to next row
        }
        return ans;
    }
}
时间: 2024-12-24 23:44:23

8.18 [LeetCode 52] N-Queens II的相关文章

[leetcode] 52. N皇后 II

52. N皇后 II 跟上个题一模一样,现在只需输出个数即可 class Solution { public int totalNQueens(int n) { boolean[] row = new boolean[n]; boolean[] h = new boolean[2 * n]; boolean[] r = new boolean[2 * n]; List<List<String>> ans = new ArrayList<>(); dfs(n, row,

leetcode#52 N queensⅡ

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回 n 皇后不同的解决方案的数量. 示例: 输入: 4 输出: 2 解释: 4 皇后问题存在如下两个不同的解法. [  [".Q..",  // 解法 1   "...Q",   "Q...",   "..Q."],  ["..Q.",  // 解法 2  

leetcode - Reverse Linked List II

leetcode - Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note:Given m, n satisfy the fol

LeetCode: Pascal&#39;s Triangle II 解题报告

Pascal's Triangle II Total Accepted: 19384 Total Submissions: 63446 My Submissions Question SolutionGiven an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to us

【leetcode】Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, givens = "catsanddog",dict = ["cat", "cats"

LeetCode:Spiral Matrix I II

Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. 打印螺旋矩阵 逐个

Leetcode | Jump Game I &amp;&amp; II

Jump Game I Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For

Leetcode | Combination Sum I &amp;&amp; II

Combination Sum I Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note:All numbers (includ

LeetCode Pascal&#39;s Triangle II (杨辉三角)

题意:给出杨辉三角的层数k,返回最后一层.k=0时就是只有一个数字1. 思路:滚动数组计算前一半出来,返回时再复制另一半.简单但是每一句都挺长的. 1 class Solution { 2 public: 3 vector<int> getRow(int rowIndex) { 4 if(rowIndex==0) return vector<int>(1,1); //0和1特殊处理 5 if(rowIndex==1) return vector<int>(2,1); 6