LeetCode: N-Queens II 解题报告

N-Queens II (LEVEL 4 难度级别,最高级5)

Follow up for N-Queens problem.

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

解答:
与第一题的解法是类似的,不同之处是,DFS的返回值是解的个数。我们每一次搜索本行8个位置时,
把8个位置的解都加在一起就行了。有的位置无解,它的返回值就是0咯。

另外注意BASE CASE:
当row == size时,也就是row越界了,这时意思是整个N-Queen都摆满了,我们这时应返回解为1.因为
你不需要任何动作,也就是唯一的解是保持原状。(虽然有点难以理解),同学可以退回到上一层来想
比如最后一行,你放置了一个皇后,它就是1个解,所以在那里dfs到下一层应该返回1.

 1 public class Solution {
 2     public int totalNQueens(int n) {
 3         if (n == 0) {
 4             return 0;
 5         }
 6
 7         // Bug 1: forget to modify the parameters of the function.
 8         return dfs(n, 0, new ArrayList<Integer>());
 9     }
10
11     public int dfs(int n, int row, ArrayList<Integer> path) {
12         if (row == n) {
13             // The base case: 当最后一行,皇后只有1种放法(就是不放)
14             return 1;
15         }
16
17         int num = 0;
18
19         // The queen can select any of the slot.
20         for (int i = 0; i < n; i++) {
21             if (!isValid(path, i)) {
22                 continue;
23             }
24             path.add(i);
25
26             // All the solutions is all the possiablities are add up.
27             num += dfs(n, row + 1, path);
28             path.remove(path.size() - 1);
29         }
30
31         return num;
32     }
33
34     public boolean isValid(ArrayList<Integer> path, int col) {
35         int size = path.size();
36         for (int i = 0; i < size; i++) {
37             // The same column with any of the current queen.
38             if (col == path.get(i)) {
39                 return false;
40             }
41
42             // diagonally lines.
43             // Bug 2: forget to add a ‘)‘
44             if (size - i == Math.abs(col - path.get(i))) {
45                 return false;
46             }
47         }
48
49         return true;
50     }
51 }

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/totalNQueens_1218_2014.java

时间: 2024-10-05 11:34:54

LeetCode: N-Queens II 解题报告的相关文章

LeetCode: Unique Paths II 解题报告

Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty spac

【LeetCode】Subsets II 解题报告

[题目] Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solutio

LeetCode: Spiral Matrix II 解题报告-三种方法解决旋转矩阵问题

Spiral Matrix IIGiven an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]] SOLUTION 1: 还是与上一题Spiral Matrix类似

LeetCode: Word Break II 解题报告

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, given s = "catsanddog", dict = ["cat",

LeetCode: Palindrome Partitioning II 解题报告

Palindrome Partitioning II Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab",Return 1 since the palindrome pa

LeetCode: Jump Game II 解题报告

Jump Game II 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. Your goal is to reach the last index in the minimum nu

LeetCode: Combination Sum II 解题报告

Combination Sum II Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note:All numbers (including ta

LeetCode: Path Sum II 解题报告

Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] SOLUTION 1: 使用

[leetcode]Contains Duplicate II解题报告 C语言

[题目] Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. [题目分析] 因为对于数值相同的两个数都距离范围研限制,那么,对每一个元素(除了最后一个元素)一一与它后面的

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