20231221 Finished

This commit is contained in:
jackfiled 2023-12-21 21:36:18 +08:00
parent d73da2a736
commit 6cbf838bd8
3 changed files with 91 additions and 1 deletions

View File

@ -6,3 +6,4 @@ mod s0002_add_two_numbers;
mod s0003_longest_substring_without_repeating_characters; mod s0003_longest_substring_without_repeating_characters;
mod s0162_find_peak_element; mod s0162_find_peak_element;
mod s2828_check_if_a_string_is_an_acronym_of_words; mod s2828_check_if_a_string_is_an_acronym_of_words;
mod s0052_n_queens_ii;

View File

@ -0,0 +1,89 @@
/**
* [52] N-Queens II
*
* The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
* Given an integer n, return the number of distinct solutions to the n-queens puzzle.
*
* <strong class="example">Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" style="width: 600px; height: 268px;" />
* Input: n = 4
* Output: 2
* Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
*
* <strong class="example">Example 2:
*
* Input: n = 1
* Output: 1
*
*
* Constraints:
*
* 1 <= n <= 9
*
*/
pub struct Solution {}
// problem: https://leetcode.cn/problems/n-queens-ii/
// discuss: https://leetcode.cn/problems/n-queens-ii/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
use std::collections::VecDeque;
impl Solution {
pub fn total_n_queens(n: i32) -> i32 {
let n = n as usize;
let mut result = 0;
let mut stack = VecDeque::new();
for i in 0..n {
stack.push_back((0usize, i, false));
}
let mut x_occupied = vec![false; n];
let mut y_occupied = vec![false; 2 * n - 1];
let mut z_occupied = vec![false; 2 * n - 1];
while let Some((x, y, flag)) = stack.pop_back() {
if flag {
x_occupied[y] = false;
y_occupied[n - 1 + x - y] = false;
z_occupied[x + y] = false;
} else {
x_occupied[y] = true;
y_occupied[n - 1 + x - y] = true;
z_occupied[x + y] = true;
stack.push_back((x, y, true));
if x == n - 1 {
result += 1;
continue;
}
for j in 0..n {
// 注意这里在判断的点是(x + 1, j)
if !x_occupied[j] && !y_occupied[n + x - j] && !z_occupied[x + 1 + j] {
stack.push_back((x + 1, j, false));
}
}
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_52() {
assert_eq!(1, Solution::total_n_queens(1));
assert_eq!(2, Solution::total_n_queens(4));
assert_eq!(14200, Solution::total_n_queens(12));
}
}

View File

@ -34,7 +34,7 @@ pub struct Solution {}
impl Solution { impl Solution {
pub fn find_peak_element(nums: Vec<i32>) -> i32 { pub fn find_peak_element(nums: Vec<i32>) -> i32 {
if nums.len() == 1 { if nums.len() == 1 {
0 return 0;
} }
let (mut left, mut right) = (0, nums.len() - 1); let (mut left, mut right) = (0, nums.len() - 1);