Leetcode Solutions (161 Part Series)
1 Solution: Next Permutation
2 Solution: Trim a Binary Search Tree
… 157 more parts…
3 Leetcode Solutions Index
4 Solution: Minimize Deviation in Array
5 Solution: Vertical Order Traversal of a Binary Tree
6 Solution: Count Ways to Make Array With Product
7 Solution: Smallest String With A Given Numeric Value
8 Solution: Linked List Cycle
9 Solution: Path With Minimum Effort
10 Solution: Concatenation of Consecutive Binary Numbers
11 Solution: Minimum Operations to Make a Subsequence
12 Solution: Longest Harmonious Subsequence
13 Solution: Simplify Path
14 Solution: Building Boxes
15 Solution: Decode XORed Permutation
16 Solution: Binary Tree Right Side View
17 Solution: Find Kth Largest XOR Coordinate Value
18 Solution: Change Minimum Characters to Satisfy One of Three Conditions
19 Solution: Shortest Distance to a Character
20 Solution: Peeking Iterator
21 Solution: Convert BST to Greater Tree
22 Solution: Copy List with Random Pointer
23 Solution: Valid Anagram
24 Solution: Number of Steps to Reduce a Number to Zero
25 Solution: Shortest Path in Binary Matrix
26 Solution: Is Graph Bipartite?
27 Solution: Maximum Score From Removing Substrings (ver. 1)
28 Solution: Maximum Score From Removing Substrings (ver. 2)
29 Solution: Sort the Matrix Diagonally
30 Solution: The K Weakest Rows in a Matrix (ver. 1)
31 Solution: The K Weakest Rows in a Matrix (ver. 2)
32 Solution: Letter Case Permutation
33 Solution: Container With Most Water
34 Solution: Arithmetic Slices
35 Solution: Minimum Remove to Make Valid Parentheses
36 Solution: Roman to Integer
37 Solution: Broken Calculator
38 Solution: Find the Most Competitive Subsequence
39 Solution: Longest Word in Dictionary through Deleting
40 Solution: Search a 2D Matrix II
41 Solution: Score of Parentheses
42 Solution: Shortest Unsorted Continuous Subarray
43 Solution: Validate Stack Sequences
44 Solution: Divide Two Integers (ver. 1)
45 Solution: Divide Two Integers (ver. 2)
46 Solution: Maximum Frequency Stack
47 Solution: Distribute Candies
48 Solution: Set Mismatch (ver. 1)
49 Solution: Set Mismatch (ver. 2)
50 Solution: Missing Number
51 Solution: Intersection of Two Linked Lists
52 Solution: Average of Levels in Binary Tree
53 Solution: Short Encoding of Words (ver. 1)
54 Solution: Design HashMap (ver. 1)
55 Solution: Short Encoding of Words (ver. 2)
56 Solution: Design HashMap (ver. 2)
57 Solution: Remove Palindromic Subsequences
58 Solution: Add One Row to Tree
59 Solution: Integer to Roman
60 Solution: Coin Change
61 Solution: Check If a String Contains All Binary Codes of Size K
62 Solution: Binary Trees With Factors
63 Solution: Swapping Nodes in a Linked List
64 Solution: Encode and Decode TinyURL
65 Solution: Best Time to Buy and Sell Stock with Transaction Fee
66 Solution: Generate Random Point in a Circle
67 Solution: Wiggle Subsequence
68 Solution: Keys and Rooms
69 Solution: Design Underground System
70 Solution: Reordered Power of 2
71 Solution: Vowel Spellchecker
72 Solution: 3Sum With Multiplicity
73 Solution: Advantage Shuffle
74 Solution: Pacific Atlantic Water Flow
75 Solution: Word Subsets
76 Solution: Palindromic Substrings
77 Solution: Reconstruct Original Digits from English
78 Solution: Flip Binary Tree To Match Preorder Traversal
79 Solution: Russian Doll Envelopes
80 Solution: Stamping The Sequence
81 Solution: Palindrome Linked List
82 Solution: Ones and Zeroes
83 Solution: Longest Valid Parentheses
84 Solution: Design Circular Queue
85 Solution: Global and Local Inversions
86 Solution: Minimum Operations to Make Array Equal
87 Solution: Determine if String Halves Are Alike
88 Solution: Letter Combinations of a Phone Number
89 Solution: Verifying an Alien Dictionary
90 Solution: Longest Increasing Path in a Matrix
91 Solution: Deepest Leaves Sum
92 Solution: Beautiful Arrangement II
93 Solution: Flatten Nested List Iterator
94 Solution: Partition List
95 Solution: Fibonacci Number
96 Solution: Remove All Adjacent Duplicates in String II
97 Solution: Number of Submatrices That Sum to Target
98 Solution: Remove Nth Node From End of List
99 Solution: Combination Sum IV
100 Solution: N-ary Tree Preorder Traversal
101 Solution: Triangle
102 Solution: Brick Wall
103 Solution: Count Binary Substrings
104 Solution: Critical Connections in a Network
105 Solution: Rotate Image
106 Solution: Furthest Building You Can Reach
107 Solution: Power of Three
108 Solution: Unique Paths II
109 Solution: Find First and Last Position of Element in Sorted Array
110 Solution: Powerful Integers
111 Solution: Prefix and Suffix Search
112 Solution: Course Schedule III
113 Solution: Running Sum of 1d Array
114 Solution: Non-decreasing Array
115 Solution: Jump Game II
116 Solution: Convert Sorted List to Binary Search Tree
117 Solution: Delete Operation for Two Strings
118 Solution: Super Palindromes
119 Solution: Construct Target Array With Multiple Sums
120 Solution: Count Primes
121 Solution: Maximum Points You Can Obtain from Cards
122 Solution: Range Sum Query 2D – Immutable
123 Solution: Ambiguous Coordinates
124 Solution: Flatten Binary Tree to Linked List
125 Solution: Valid Number
126 Solution: Binary Tree Cameras
127 Solution: Longest String Chain
128 Solution: Find Duplicate File in System
129 Solution: Minimum Moves to Equal Array Elements II
130 Solution: Binary Tree Level Order Traversal
131 Solution: Find and Replace Pattern
132 Solution: N-Queens
133 Solution: To Lower Case
134 Solution: Evaluate Reverse Polish Notation
135 Solution: Partitioning Into Minimum Number Of Deci-Binary Numbers
136 Solution: Maximum Product of Word Lengths
137 Solution: Maximum Erasure Value
138 Solution: N-Queens II
139 Solution: Maximum Gap
140 Solution: Search Suggestions System
141 Solution: Max Area of Island
142 Solution: Interleaving String
143 Solution: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
144 Solution: Open the Lock
145 Solution: Maximum Performance of a Team
146 Solution: Longest Consecutive Sequence
147 Solution: Min Cost Climbing Stairs
148 Solution: Construct Binary Tree from Preorder and Inorder Traversal
149 Solution: Jump Game VI
150 Solution: My Calendar I
151 Solution: Stone Game VII
152 Solution: Minimum Number of Refueling Stops
153 Solution: Palindrome Pairs
154 Solution: Maximum Units on a Truck
155 Solution: Matchsticks to Square
156 Solution: Generate Parentheses
157 Solution: Number of Subarrays with Bounded Maximum
158 Solution: Swim in Rising Water
159 Solution: Pascal’s Triangle
160 Solution: Out of Boundary Paths
161 Solution: Redundant Connection
This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode’s forums.
Leetcode Problem #51 (Hard): N-Queens
Description:
(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)
The n-queens puzzle is the problem of placing
n
queens on ann x n
chessboard such that no two queens attack each other.Given an integer
n
, return all distinct solutions to the n-queens puzzle.Each solution contains a distinct board configuration of the n-queens’ placement, where
'Q'
and'.'
both indicate a queen and an empty space, respectively.
Examples:
Example 1: Input: n = 4 Output: [[“.Q..”,”…Q”,”Q…”,”..Q.”],[“..Q.”,”Q…”,”…Q”,”.Q..”]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Visual:
Example 2: Input: n = 1 Output: [[“Q”]]
Constraints:
1 <= n <= 9
Idea:
(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)
A naive approach here would attempt every possible combination of locations, but there are (N^2)! / (N^2 – N)! different combinations, which is up to ~1e17 when N = 9. Instead, we need to make sure we only attempt to place queens where it’s feasible to do so, based on the instructions. This would seem to call for a depth first search (DFS) approach with a recursive helper function (place), so that we only pursue workable combinations without wasting time on known dead-ends.
First, we should consider how the queens will be placed. Since each row can only have one queen, our basic process will be to place a queen and then recurse to the next row. On each row, we’ll have to iterate through the possible options, check the cell for validity, then place the queen on the board. Once the recursion returns, we can backtrack and iterate to the next cell in the row.
Since a queen has four axes of attack, we’ll need to check the three remaining axes (other than the horizontal row, which our iteration will naturally take care of) for validity. There are N possible columns and 2 * N – 1 possible left-downward diagonals and right-downward diagonals. With a constraint of 1 <= N <= 9, each of the two diagonal states represents up to 17 bits‘ worth of data and the vertical state up to 9 bits, so we can use bit manipulation to store these states efficiently.
So for each recursive call to place a queen, we should pass along the board state in the form of only three integers (vert, ldiag, rdiag). We can then use bitmasks to check for cell validity before attempting to recurse to the next row.
Since our board is an N^2 matrix, we can use backtracking here to good effect. If we successfully reach the end of the board without failing, we should push a copy of board with the rows as strings onto our answer array (ans). (Note: It is possible to lower the extra space to only the size of the recursion stack, O(N), by procedurally generating the results directly in ans, but it doesn’t represent a great deal of space savings compared to the extra processing it requires.)
- Time Complexity: O(N!) which represents the maximum number of queens placed
- Space Complexity: O(N^2) for the board
Javascript Code:
(Jump to: Problem Description || Solution Idea)
var solveNQueens = function(N) {
let ans = [],
board = Array.from({length: N}, () => new Array(N).fill('.'))
const place = (i, vert, ldiag, rdiag) => {
if (i === N) {
let res = new Array(N)
for (let row = 0; row < N; row++)
res[row] = board[row].join("")
ans.push(res)
return
}
for (let j = 0; j < N; j++) {
let vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j)
if (vert & vmask || ldiag & lmask || rdiag & rmask) continue
board[i][j] = 'Q'
place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask)
board[i][j] = '.'
}
}
place(0,0,0,0)
return ans
};
Enter fullscreen mode Exit fullscreen mode
Python Code:
(Jump to: Problem Description || Solution Idea)
class Solution:
def solveNQueens(self, N: int) -> List[List[str]]:
ans = []
board = [['.'] * N for _ in range(N)]
def place(i: int, vert: int, ldiag: int, rdiag:int) -> None:
if i == N:
ans.append(["".join(row) for row in board])
return
for j in range(N):
vmask, lmask, rmask = 1 << j, 1 << (i+j), 1 << (N-i-1+j)
if vert & vmask or ldiag & lmask or rdiag & rmask: continue
board[i][j] = 'Q'
place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask)
board[i][j] = '.'
place(0,0,0,0)
return ans
Enter fullscreen mode Exit fullscreen mode
Java Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
List<List<String>> ans;
char[][] board;
public List<List<String>> solveNQueens(int N) {
ans = new ArrayList<>();
board = new char[N][N];
for (char[] row : board) Arrays.fill(row, '.');
place(0,0,0,0);
return ans;
}
private void place(int i, int vert, int ldiag, int rdiag) {
int N = board.length;
if (i == N) {
List<String> res = new ArrayList<>();
for (char[] row : board) res.add(new String(row));
ans.add(res);
return;
}
for (int j = 0; j < N; j++) {
int vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j);
if ((vert & vmask) + (ldiag & lmask) + (rdiag & rmask) > 0) continue;
board[i][j] = 'Q';
place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask);
board[i][j] = '.';
}
}
}
Enter fullscreen mode Exit fullscreen mode
C++ Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
public:
vector<vector<string>> solveNQueens(int N) {
ans.clear();
board.resize(N, string(N, '.'));
place(0,0,0,0);
return ans;
}
private:
vector<vector<string>> ans;
vector<string> board;
void place(int i, int vert, int ldiag, int rdiag) {
int N = board.size();
if (i == N) {
vector<string> res;
for (auto row : board) res.push_back(row);
ans.push_back(res);
return;
}
for (int j = 0; j < N; j++) {
int vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j);
if (vert & vmask || ldiag & lmask || rdiag & rmask) continue;
board[i][j] = 'Q';
place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask);
board[i][j] = '.';
}
}
};
Enter fullscreen mode Exit fullscreen mode
Leetcode Solutions (161 Part Series)
1 Solution: Next Permutation
2 Solution: Trim a Binary Search Tree
… 157 more parts…
3 Leetcode Solutions Index
4 Solution: Minimize Deviation in Array
5 Solution: Vertical Order Traversal of a Binary Tree
6 Solution: Count Ways to Make Array With Product
7 Solution: Smallest String With A Given Numeric Value
8 Solution: Linked List Cycle
9 Solution: Path With Minimum Effort
10 Solution: Concatenation of Consecutive Binary Numbers
11 Solution: Minimum Operations to Make a Subsequence
12 Solution: Longest Harmonious Subsequence
13 Solution: Simplify Path
14 Solution: Building Boxes
15 Solution: Decode XORed Permutation
16 Solution: Binary Tree Right Side View
17 Solution: Find Kth Largest XOR Coordinate Value
18 Solution: Change Minimum Characters to Satisfy One of Three Conditions
19 Solution: Shortest Distance to a Character
20 Solution: Peeking Iterator
21 Solution: Convert BST to Greater Tree
22 Solution: Copy List with Random Pointer
23 Solution: Valid Anagram
24 Solution: Number of Steps to Reduce a Number to Zero
25 Solution: Shortest Path in Binary Matrix
26 Solution: Is Graph Bipartite?
27 Solution: Maximum Score From Removing Substrings (ver. 1)
28 Solution: Maximum Score From Removing Substrings (ver. 2)
29 Solution: Sort the Matrix Diagonally
30 Solution: The K Weakest Rows in a Matrix (ver. 1)
31 Solution: The K Weakest Rows in a Matrix (ver. 2)
32 Solution: Letter Case Permutation
33 Solution: Container With Most Water
34 Solution: Arithmetic Slices
35 Solution: Minimum Remove to Make Valid Parentheses
36 Solution: Roman to Integer
37 Solution: Broken Calculator
38 Solution: Find the Most Competitive Subsequence
39 Solution: Longest Word in Dictionary through Deleting
40 Solution: Search a 2D Matrix II
41 Solution: Score of Parentheses
42 Solution: Shortest Unsorted Continuous Subarray
43 Solution: Validate Stack Sequences
44 Solution: Divide Two Integers (ver. 1)
45 Solution: Divide Two Integers (ver. 2)
46 Solution: Maximum Frequency Stack
47 Solution: Distribute Candies
48 Solution: Set Mismatch (ver. 1)
49 Solution: Set Mismatch (ver. 2)
50 Solution: Missing Number
51 Solution: Intersection of Two Linked Lists
52 Solution: Average of Levels in Binary Tree
53 Solution: Short Encoding of Words (ver. 1)
54 Solution: Design HashMap (ver. 1)
55 Solution: Short Encoding of Words (ver. 2)
56 Solution: Design HashMap (ver. 2)
57 Solution: Remove Palindromic Subsequences
58 Solution: Add One Row to Tree
59 Solution: Integer to Roman
60 Solution: Coin Change
61 Solution: Check If a String Contains All Binary Codes of Size K
62 Solution: Binary Trees With Factors
63 Solution: Swapping Nodes in a Linked List
64 Solution: Encode and Decode TinyURL
65 Solution: Best Time to Buy and Sell Stock with Transaction Fee
66 Solution: Generate Random Point in a Circle
67 Solution: Wiggle Subsequence
68 Solution: Keys and Rooms
69 Solution: Design Underground System
70 Solution: Reordered Power of 2
71 Solution: Vowel Spellchecker
72 Solution: 3Sum With Multiplicity
73 Solution: Advantage Shuffle
74 Solution: Pacific Atlantic Water Flow
75 Solution: Word Subsets
76 Solution: Palindromic Substrings
77 Solution: Reconstruct Original Digits from English
78 Solution: Flip Binary Tree To Match Preorder Traversal
79 Solution: Russian Doll Envelopes
80 Solution: Stamping The Sequence
81 Solution: Palindrome Linked List
82 Solution: Ones and Zeroes
83 Solution: Longest Valid Parentheses
84 Solution: Design Circular Queue
85 Solution: Global and Local Inversions
86 Solution: Minimum Operations to Make Array Equal
87 Solution: Determine if String Halves Are Alike
88 Solution: Letter Combinations of a Phone Number
89 Solution: Verifying an Alien Dictionary
90 Solution: Longest Increasing Path in a Matrix
91 Solution: Deepest Leaves Sum
92 Solution: Beautiful Arrangement II
93 Solution: Flatten Nested List Iterator
94 Solution: Partition List
95 Solution: Fibonacci Number
96 Solution: Remove All Adjacent Duplicates in String II
97 Solution: Number of Submatrices That Sum to Target
98 Solution: Remove Nth Node From End of List
99 Solution: Combination Sum IV
100 Solution: N-ary Tree Preorder Traversal
101 Solution: Triangle
102 Solution: Brick Wall
103 Solution: Count Binary Substrings
104 Solution: Critical Connections in a Network
105 Solution: Rotate Image
106 Solution: Furthest Building You Can Reach
107 Solution: Power of Three
108 Solution: Unique Paths II
109 Solution: Find First and Last Position of Element in Sorted Array
110 Solution: Powerful Integers
111 Solution: Prefix and Suffix Search
112 Solution: Course Schedule III
113 Solution: Running Sum of 1d Array
114 Solution: Non-decreasing Array
115 Solution: Jump Game II
116 Solution: Convert Sorted List to Binary Search Tree
117 Solution: Delete Operation for Two Strings
118 Solution: Super Palindromes
119 Solution: Construct Target Array With Multiple Sums
120 Solution: Count Primes
121 Solution: Maximum Points You Can Obtain from Cards
122 Solution: Range Sum Query 2D – Immutable
123 Solution: Ambiguous Coordinates
124 Solution: Flatten Binary Tree to Linked List
125 Solution: Valid Number
126 Solution: Binary Tree Cameras
127 Solution: Longest String Chain
128 Solution: Find Duplicate File in System
129 Solution: Minimum Moves to Equal Array Elements II
130 Solution: Binary Tree Level Order Traversal
131 Solution: Find and Replace Pattern
132 Solution: N-Queens
133 Solution: To Lower Case
134 Solution: Evaluate Reverse Polish Notation
135 Solution: Partitioning Into Minimum Number Of Deci-Binary Numbers
136 Solution: Maximum Product of Word Lengths
137 Solution: Maximum Erasure Value
138 Solution: N-Queens II
139 Solution: Maximum Gap
140 Solution: Search Suggestions System
141 Solution: Max Area of Island
142 Solution: Interleaving String
143 Solution: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
144 Solution: Open the Lock
145 Solution: Maximum Performance of a Team
146 Solution: Longest Consecutive Sequence
147 Solution: Min Cost Climbing Stairs
148 Solution: Construct Binary Tree from Preorder and Inorder Traversal
149 Solution: Jump Game VI
150 Solution: My Calendar I
151 Solution: Stone Game VII
152 Solution: Minimum Number of Refueling Stops
153 Solution: Palindrome Pairs
154 Solution: Maximum Units on a Truck
155 Solution: Matchsticks to Square
156 Solution: Generate Parentheses
157 Solution: Number of Subarrays with Bounded Maximum
158 Solution: Swim in Rising Water
159 Solution: Pascal’s Triangle
160 Solution: Out of Boundary Paths
161 Solution: Redundant Connection
原文链接:Solution: N-Queens
暂无评论内容