From 26376b6417a102e883071452c9863982f1d77802 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sun, 17 Jul 2022 10:53:14 +0800 Subject: [PATCH 01/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200093.=E5=A4=8D?= =?UTF-8?q?=E5=8E=9FIP=E5=9C=B0=E5=9D=80=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0093.复原IP地址 Rust版本 --- problems/0093.复原IP地址.md | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 11ca2d03..46ac1c86 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -536,6 +536,53 @@ func isNormalIp(s string,startIndex,end int)bool{ ``` +## Rust + +```Rust +impl Solution { + fn is_valid(s: &Vec, start: usize, end: usize) -> bool { + if start > end { return false; } + if s[start] == '0' && start != end { return false; } + let mut num = 0; + for i in start..=end { + if s[i] > '9' || s[i] < '0' { return false; } + if let Some(digit) = s[i].to_digit(10) { num = num * 10 + digit; } + if num > 255 { return false; } + } + true + } + + fn backtracking(result: &mut Vec, s: &mut Vec, start_index: usize, mut point_num: usize) { + let len = s.len(); + if point_num == 3 { + if Self::is_valid(s, start_index, len - 1) { + result.push(s.iter().collect::()); + } + return; + } + for i in start_index..len { + if Self::is_valid(s, start_index, i) { + point_num += 1; + s.insert(i + 1, '.'); + Self::backtracking(result, s, i + 2, point_num); + point_num -= 1; + s.remove(i + 1); + } else { break; } + } + } + + pub fn restore_ip_addresses(s: String) -> Vec { + let mut result: Vec = Vec::new(); + let len = s.len(); + if len < 4 || len > 12 { return result; } + let mut s = s.chars().collect::>(); + Self::backtracking(&mut result, &mut s, 0, 0); + result + } + +} +``` + ## C ```c //记录结果 From aaac4825ec0f638b07e6772829bc25a26f677863 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Mon, 18 Jul 2022 09:46:46 +0800 Subject: [PATCH 02/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200078.=E5=AD=90?= =?UTF-8?q?=E9=9B=86=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0078.子集 Rust版本 --- problems/0078.子集.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index e6cc668b..3e98311e 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -292,6 +292,30 @@ function subsets(nums: number[]): number[][] { }; ``` +## Rust + +```Rust +impl Solution { + fn backtracking(result: &mut Vec>, path: &mut Vec, nums: &Vec, start_index: usize) { + result.push(path.clone()); + let len = nums.len(); + // if start_index >= len { return; } + for i in start_index..len { + path.push(nums[i]); + Self::backtracking(result, path, nums, i + 1); + path.pop(); + } + } + + pub fn subsets(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + Self::backtracking(&mut result, &mut path, &nums, 0); + result + } +} +``` + ## C ```c From ac4bdf21015d0bdcd72522b4190158b36deea391 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 19 Jul 2022 09:40:59 +0800 Subject: [PATCH 03/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200090.=E5=AD=90?= =?UTF-8?q?=E9=9B=86II=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0090.子集II Rust版本 --- problems/0090.子集II.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index e85ec66d..7ab6afb6 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -340,6 +340,36 @@ function subsetsWithDup(nums: number[]): number[][] { }; ``` +### Rust + +```Rust +impl Solution { + fn backtracking(result: &mut Vec>, path: &mut Vec, nums: &Vec, start_index: usize, used: &mut Vec) { + result.push(path.clone()); + let len = nums.len(); + // if start_index >= len { return; } + for i in start_index..len { + if i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false { continue; } + path.push(nums[i]); + used[i] = true; + Self::backtracking(result, path, nums, i + 1, used); + used[i] = false; + path.pop(); + } + } + + pub fn subsets_with_dup(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + let mut used = vec![false; nums.len()]; + let mut nums = nums; + nums.sort(); + Self::backtracking(&mut result, &mut path, &nums, 0, &mut used); + result + } +} +``` + ### C ```c From 90ff8a8ff85752d865a458d9ff68c41ce9e3de21 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Wed, 20 Jul 2022 15:00:40 +0800 Subject: [PATCH 04/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200491.=E9=80=92?= =?UTF-8?q?=E5=A2=9E=E5=AD=90=E5=BA=8F=E5=88=97=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0491.递增子序列 Rust版本 --- problems/0491.递增子序列.md | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 080984f2..6a92aa21 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -423,6 +423,57 @@ function findSubsequences(nums: number[]): number[][] { }; ``` +### Rust +**回溯+哈希** +```Rust +use std::collections::HashSet; +impl Solution { + fn backtracking(result: &mut Vec>, path: &mut Vec, nums: &Vec, start_index: usize) { + if path.len() > 1 { result.push(path.clone()); } + let len = nums.len(); + let mut uset: HashSet = HashSet::new(); + for i in start_index..len { + if (!path.is_empty() && nums[i] < *path.last().unwrap()) || uset.contains(&nums[i]) { continue; } + uset.insert(nums[i]); + path.push(nums[i]); + Self::backtracking(result, path, nums, i + 1); + path.pop(); + } + } + + pub fn find_subsequences(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + Self::backtracking(&mut result, &mut path, &nums, 0); + result + } +} +``` +**回溯+数组** +```Rust +impl Solution { + fn backtracking(result: &mut Vec>, path: &mut Vec, nums: &Vec, start_index: usize) { + if path.len() > 1 { result.push(path.clone()); } + let len = nums.len(); + let mut used = [0; 201]; + for i in start_index..len { + if (!path.is_empty() && nums[i] < *path.last().unwrap()) || used[(nums[i] + 100) as usize] == 1 { continue; } + used[(nums[i] + 100) as usize] = 1; + path.push(nums[i]); + Self::backtracking(result, path, nums, i + 1); + path.pop(); + } + } + + pub fn find_subsequences(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + Self::backtracking(&mut result, &mut path, &nums, 0); + result + } +} +``` + ### C ```c From dcb4ff10a36ef93f2f2d0f099df2c3e8d912421a Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Fri, 22 Jul 2022 09:56:34 +0800 Subject: [PATCH 05/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200047.=E5=85=A8?= =?UTF-8?q?=E6=8E=92=E5=88=97II=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0047.全排列II Rust版本 --- problems/0047.全排列II.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index 88680c8c..2c3f579f 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -351,6 +351,40 @@ func permuteUnique(_ nums: [Int]) -> [[Int]] { } ``` +### Rust + +```Rust +impl Solution { + fn backtracking(result: &mut Vec>, path: &mut Vec, nums: &Vec, used: &mut Vec) { + let len = nums.len(); + if path.len() == len { + result.push(path.clone()); + return; + } + for i in 0..len { + if i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false { continue; } + if used[i] == false { + used[i] = true; + path.push(nums[i]); + Self::backtracking(result, path, nums, used); + path.pop(); + used[i] = false; + } + } + } + + pub fn permute_unique(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + let mut used = vec![false; nums.len()]; + let mut nums= nums; + nums.sort(); + Self::backtracking(&mut result, &mut path, &nums, &mut used); + result + } +} +``` + ### C ```c //临时数组 From b193edc5a8f8489352dfe61fcb8d73ba1c29dd54 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sat, 23 Jul 2022 20:55:18 +0800 Subject: [PATCH 06/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200332.=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B=20Rust=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0332.重新安排行程 Rust版本 --- problems/0332.重新安排行程.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 71942c79..8b5f797d 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -742,5 +742,33 @@ func (p ticketSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } ``` +### Rust +** 文中的Hashmap嵌套Hashmap的方法因为Rust的所有权问题暂时无法实现,此方法为删除哈希表中元素法 ** +```Rust +use std::collections::HashMap; +impl Solution { + fn backtracking(airport: String, targets: &mut HashMap<&String, Vec<&String>>, result: &mut Vec) { + while let Some(next_airport) = targets.get_mut(&airport).unwrap_or(&mut vec![]).pop() { + Self::backtracking(next_airport.clone(), targets, result); + } + result.push(airport.clone()); + } + + pub fn find_itinerary(tickets: Vec>) -> Vec { + let mut targets: HashMap<&String, Vec<&String>> = HashMap::new(); + let mut result = Vec::new(); + for t in 0..tickets.len() { + targets.entry(&tickets[t][0]).or_default().push(&tickets[t][1]); + } + for (_, target) in targets.iter_mut() { + target.sort_by(|a, b| b.cmp(a)); + } + Self::backtracking("JFK".to_string(), &mut targets, &mut result); + result.reverse(); + result + } +} +``` + -----------------------
From 8e65f2e02497f7b78b2df85bc8de5788bec840e4 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sun, 24 Jul 2022 22:13:45 +0800 Subject: [PATCH 07/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200051.N=E7=9A=87?= =?UTF-8?q?=E5=90=8E=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0051.N皇后 Rust版本 --- problems/0051.N皇后.md | 50 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 9ae1f975..77a2ca59 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -558,6 +558,56 @@ func solveNQueens(_ n: Int) -> [[String]] { } ``` +### Rust + +```Rust +impl Solution { + fn is_valid(row: usize, col: usize, chessboard: &mut Vec>, n: usize) -> bool { + let mut i = 0 as usize; + while i < row { + if chessboard[i][col] == 'Q' { return false; } + i += 1; + } + let (mut i, mut j) = (row as i32 - 1, col as i32 - 1); + while i >= 0 && j >= 0 { + if chessboard[i as usize][j as usize] == 'Q' { return false; } + i -= 1; + j -= 1; + } + let (mut i, mut j) = (row as i32 - 1, col as i32 + 1); + while i >= 0 && j < n as i32 { + if chessboard[i as usize][j as usize] == 'Q' { return false; } + i -= 1; + j += 1; + } + return true; + } + fn backtracking(result: &mut Vec>, n: usize, row: usize, chessboard: &mut Vec>) { + if row == n { + let mut chessboard_clone: Vec = Vec::new(); + for i in chessboard { + chessboard_clone.push(i.iter().collect::()); + } + result.push(chessboard_clone); + return; + } + for col in 0..n { + if Self::is_valid(row, col, chessboard, n) { + chessboard[row][col] = 'Q'; + Self::backtracking(result, n, row + 1, chessboard); + chessboard[row][col] = '.'; + } + } + } + pub fn solve_n_queens(n: i32) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut chessboard: Vec> = vec![vec!['.'; n as usize]; n as usize]; + Self::backtracking(&mut result, n as usize, 0, &mut chessboard); + result + } +} +``` + ### C ```c char ***ans; From fd099c827574310dc9c7f8cf21578bd68d822b98 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Mon, 25 Jul 2022 20:05:22 +0800 Subject: [PATCH 08/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200037.=E8=A7=A3?= =?UTF-8?q?=E6=95=B0=E7=8B=AC=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0037.解数独 Rust版本 --- problems/0037.解数独.md | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 626e9d97..8b196890 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -488,6 +488,52 @@ function solveSudoku(board: string[][]): void { }; ``` +### Rust + +```Rust +impl Solution { + fn is_valid(row: usize, col: usize, val: char, board: &mut Vec>) -> bool{ + for i in 0..9 { + if board[row][i] == val { return false; } + } + for j in 0..9 { + if board[j][col] == val { + return false; + } + } + let start_row = (row / 3) * 3; + let start_col = (col / 3) * 3; + for i in start_row..(start_row + 3) { + for j in start_col..(start_col + 3) { + if board[i][j] == val { return false; } + } + } + return true; + } + + fn backtracking(board: &mut Vec>) -> bool{ + for i in 0..board.len() { + for j in 0..board[0].len() { + if board[i][j] != '.' { continue; } + for k in '1'..='9' { + if Self::is_valid(i, j, k, board) { + board[i][j] = k; + if Self::backtracking(board) { return true; } + board[i][j] = '.'; + } + } + return false; + } + } + return true; + } + + pub fn solve_sudoku(board: &mut Vec>) { + Self::backtracking(board); + } +} +``` + ### C ```C From b80591ef85f2efb1f0917c7e0144bc7f5f15e81f Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 26 Jul 2022 10:35:31 +0800 Subject: [PATCH 09/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200122.=E4=B9=B0?= =?UTF-8?q?=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6?= =?UTF-8?q?=E6=9C=BAII=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0122.买卖股票的最佳时机II Rust版本(贪心+动态规划) --- .../0122.买卖股票的最佳时机II.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index e4742cf0..1094d9e4 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -282,6 +282,43 @@ function maxProfit(prices: number[]): number { }; ``` +### Rust + +贪心: +```Rust +impl Solution { + fn max(a: i32, b: i32) -> i32 { + if a > b { a } else { b } + } + pub fn max_profit(prices: Vec) -> i32 { + let mut result = 0; + for i in 1..prices.len() { + result += Self::max(prices[i] - prices[i - 1], 0); + } + result + } +} +``` + +动态规划: +```Rust +impl Solution { + fn max(a: i32, b: i32) -> i32 { + if a > b { a } else { b } + } + pub fn max_profit(prices: Vec) -> i32 { + let n = prices.len(); + let mut dp = vec![vec![0; 2]; n]; + dp[0][0] -= prices[0]; + for i in 1..n { + dp[i][0] = Self::max(dp[i - 1][0], dp[i - 1][1] - prices[i]); + dp[i][1] = Self::max(dp[i - 1][1], dp[i - 1][0] + prices[i]); + } + Self::max(dp[n - 1][0], dp[n - 1][1]) + } +} +``` + ### C: 贪心: ```c From fdfddd88f99400442d5bc815df0adea96cb8589a Mon Sep 17 00:00:00 2001 From: firemaples Date: Tue, 26 Jul 2022 22:37:40 +0800 Subject: [PATCH 10/18] =?UTF-8?q?Update=200452.=E7=94=A8=E6=9C=80=E5=B0=91?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E7=9A=84=E7=AE=AD=E5=BC=95=E7=88=86=E6=B0=94?= =?UTF-8?q?=E7=90=83.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a missing line back --- problems/0452.用最少数量的箭引爆气球.md | 1 + 1 file changed, 1 insertion(+) diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index 3042b063..6e092f7c 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -150,6 +150,7 @@ class Solution { int count = 1; //重叠气球的最小右边界 int leftmostRightBound = points[0][1]; + for (int i = 1; i < points.length; i++) { //如果下一个气球的左边界大于最小右边界 if (points[i][0] > leftmostRightBound ) { //增加一次射击 From 5ea4ec6829730a2cba0c8fec7009e0c3b82d238c Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Wed, 27 Jul 2022 16:20:17 +0800 Subject: [PATCH 11/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200055.=E8=B7=B3?= =?UTF-8?q?=E8=B7=83=E6=B8=B8=E6=88=8F=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0055.跳跃游戏 Rust版本 --- problems/0055.跳跃游戏.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index e7c4f5a2..394117ee 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -154,6 +154,26 @@ var canJump = function(nums) { }; ``` +### Rust + +```Rust +impl Solution { + fn max(a: usize, b: usize) -> usize { + if a > b { a } else { b } + } + pub fn can_jump(nums: Vec) -> bool { + let mut cover = 0; + if (nums.len() == 1) { return true; } + let mut i = 0; + while i <= cover { + cover = Self::max(i + nums[i] as usize, cover); + if cover >= nums.len() - 1 { return true; } + i += 1; + } + false + } +} +``` ### C ```c From d7df0cbb0e7153e170f9d5c7a96bfda9052f1dc7 Mon Sep 17 00:00:00 2001 From: chaoswang <73639170+chaos0156@users.noreply.github.com> Date: Thu, 28 Jul 2022 11:34:36 +0800 Subject: [PATCH 12/18] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer58-II.?= =?UTF-8?q?=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer58-II.左旋转字符串.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index de4a9030..bf5d3f90 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -263,6 +263,13 @@ function reverseLeftWords(s: string, n: number): string { return strArr.join(''); }; ``` +方法二: +```typescript +// 拼接两个字符串,截取符合要求的部分 +function reverseLeftWords(s: string, n: number): string { + return (s+s).slice(n,s.length+n); +}; +``` Swift: From ae39e59255a56e8ba4285a0b5b843716c28d1317 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Thu, 28 Jul 2022 17:45:30 +0800 Subject: [PATCH 13/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200045.=E8=B7=B3?= =?UTF-8?q?=E8=B7=83=E6=B8=B8=E6=88=8FII=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0045.跳跃游戏II Rust版本 --- problems/0045.跳跃游戏II.md | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index 648355fd..13142c99 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -305,6 +305,56 @@ object Solution { } ``` +### Rust + +```Rust +//版本一 +impl Solution { + fn max(a: i32, b:i32) -> i32 { + if a > b { a } else { b } + } + pub fn jump(nums: Vec) -> i32 { + if nums.len() == 0 { return 0; } + let mut cur_distance: i32 = 0; + let mut ans: i32 = 0; + let mut next_distance: i32 = 0; + for i in 0..nums.len() { + next_distance = Self::max(nums[i] + i as i32, next_distance); + if i as i32 == cur_distance { + if cur_distance != (nums.len() - 1) as i32 { + ans += 1; + cur_distance = next_distance; + if next_distance == (nums.len() - 1) as i32 { break; } + } + else { break; } + } + } + ans + } +} +``` + +```Rust +//版本二 +impl Solution { + fn max(a: i32, b:i32) -> i32 { + if a > b { a } else { b } + } + pub fn jump(nums: Vec) -> i32 { + let mut cur_distance: i32 = 0; + let mut ans: i32 = 0; + let mut next_distance: i32 = 0; + for i in 0..nums.len() - 1 { + next_distance = Self::max(nums[i] + i as i32, next_distance); + if i as i32 == cur_distance { + cur_distance = next_distance; + ans += 1; + } + } + ans + } +} +``` ----------------------- From 28aef25b6122b2f676546276ab51d1fccf82cbcf Mon Sep 17 00:00:00 2001 From: Caesar-Wei <65577839+Caesar-Wei@users.noreply.github.com> Date: Thu, 28 Jul 2022 22:55:05 -0400 Subject: [PATCH 14/18] =?UTF-8?q?Update=200031.=E4=B8=8B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=8E=92=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fixed bug in python solution and display issues --- problems/0031.下一个排列.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 1a3641b0..4f49ce74 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -136,10 +136,10 @@ class Solution: >另一种思路 ```python class Solution: - ''' - 抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用。 - 故选择另一种算法暂且提供一种python思路 - ''' + ''' + 抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用。 + 故选择另一种算法暂且提供一种python思路 + ''' def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. @@ -153,9 +153,9 @@ class Solution: break self.reverse(nums, i, length-1) break - else: - # 若正常结束循环,则对原数组直接翻转 - self.reverse(nums, 0, length-1) + if n == 1: + # 若正常结束循环,则对原数组直接翻转 + self.reverse(nums, 0, length-1) def reverse(self, nums: List[int], low: int, high: int) -> None: while low < high: @@ -164,7 +164,7 @@ class Solution: high -= 1 ``` >上一版本简化版 -'''python +```python class Solution(object): def nextPermutation(self, nums: List[int]) -> None: n = len(nums) @@ -185,7 +185,7 @@ class Solution(object): end -= 1 return nums -''' +``` ## Go From 50d497a834658168e616c7611438b622bdf58fad Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Fri, 29 Jul 2022 18:49:28 +0800 Subject: [PATCH 15/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=201005.K=E6=AC=A1?= =?UTF-8?q?=E5=8F=96=E5=8F=8D=E5=90=8E=E6=9C=80=E5=A4=A7=E5=8C=96=E7=9A=84?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E5=92=8C=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 1005.K次取反后最大化的数组和 Rust版本 --- ...1005.K次取反后最大化的数组和.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 8d721b9f..9d82bf9f 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -227,6 +227,31 @@ var largestSumAfterKNegations = function(nums, k) { }; ``` +### Rust + +```Rust +impl Solution { + pub fn largest_sum_after_k_negations(nums: Vec, k: i32) -> i32 { + let mut nums = nums; + let mut k = k; + let len = nums.len(); + nums.sort_by(|a, b| b.abs().cmp(&a.abs())); + for i in 0..len { + if nums[i] < 0 && k > 0 { + nums[i] *= -1; + k -= 1; + } + } + if k % 2 == 1 { nums[len - 1] *= -1; } + let mut result = 0; + for num in nums { + result += num; + } + result + } +} +``` + ### C ```c From 35ac776a7d8769ff2c13c0c233e20bdff52addb2 Mon Sep 17 00:00:00 2001 From: wjchahaha <1678912421@qq.com> Date: Tue, 9 Aug 2022 19:04:10 +0800 Subject: [PATCH 16/18] =?UTF-8?q?=E6=9B=B4=E6=94=B9ACM=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E4=B8=8B=E5=A6=82=E4=BD=95=E6=9E=84=E5=BB=BA=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91BUG,=E4=BF=AE=E6=94=B9java&C++=E4=BB=A3=E7=A0=81.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../前序/ACM模式如何构建二叉树.md | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/problems/前序/ACM模式如何构建二叉树.md b/problems/前序/ACM模式如何构建二叉树.md index f2aafed6..01d5b255 100644 --- a/problems/前序/ACM模式如何构建二叉树.md +++ b/problems/前序/ACM模式如何构建二叉树.md @@ -57,11 +57,18 @@ TreeNode* construct_binary_tree(const vector& vec) { if (i == 0) root = node; } // 遍历一遍,根据规则左右孩子赋值就可以了 - // 注意这里 结束规则是 i * 2 + 2 < vec.size(),避免空指针 - for (int i = 0; i * 2 + 2 < vec.size(); i++) { + // 注意这里 结束规则是 i * 2 + 1 < vec.size(),避免空指针 + // 为什么结束规则不能是i * 2 + 2 < arr.length呢? + // 如果i * 2 + 2 < arr.length 是结束条件 + // 那么i * 2 + 1这个符合条件的节点就被忽略掉了 + // 例如[2,7,9,-1,1,9,6,-1,-1,10] 这样的一个二叉树,最后的10就会被忽略掉 + // 遍历一遍,根据规则左右孩子赋值就可以了 + + for (int i = 0; i * 2 + 1 < vec.size(); i++) { if (vecTree[i] != NULL) { // 线性存储转连式存储关键逻辑 vecTree[i]->left = vecTree[i * 2 + 1]; + if(i * 2 + 2 < vec.size()) vecTree[i]->right = vecTree[i * 2 + 2]; } } @@ -114,9 +121,10 @@ TreeNode* construct_binary_tree(const vector& vec) { vecTree[i] = node; if (i == 0) root = node; } - for (int i = 0; i * 2 + 2 < vec.size(); i++) { + for (int i = 0; i * 2 + 1 < vec.size(); i++) { if (vecTree[i] != NULL) { vecTree[i]->left = vecTree[i * 2 + 1]; + if(i * 2 + 2 < vec.size()) vecTree[i]->right = vecTree[i * 2 + 2]; } } @@ -213,7 +221,7 @@ public class Solution { static class TreeNode { // 节点值 int val; - + // 左节点 TreeNode left; @@ -249,12 +257,18 @@ public class Solution { } } // 遍历一遍,根据规则左右孩子赋值就可以了 - // 注意这里 结束规则是 i * 2 + 2 < arr.length,避免空指针 - for (int i = 0; i * 2 + 2 < arr.length; i++) { + // 注意这里 结束规则是 i * 2 + 1 < arr.length,避免空指针 + // 为什么结束规则不能是i * 2 + 2 < arr.length呢? + // 如果i * 2 + 2 < arr.length 是结束条件 + // 那么i * 2 + 1这个符合条件的节点就被忽略掉了 + // 例如[2,7,9,-1,1,9,6,-1,-1,10] 这样的一个二叉树,最后的10就会被忽略掉 + for (int i = 0; i * 2 + 1 < arr.length; i++) { TreeNode node = treeNodeList.get(i); if (node != null) { // 线性存储转连式存储关键逻辑 node.left = treeNodeList.get(2 * i + 1); + // 再次判断下 不忽略任何一个节点 + if(i * 2 + 2 < arr.length) node.right = treeNodeList.get(2 * i + 2); } } From d8bbb1284d8122cff0d10fbb2149e6eee40e132f Mon Sep 17 00:00:00 2001 From: wurui Date: Thu, 11 Aug 2022 17:39:41 +0800 Subject: [PATCH 17/18] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=E7=9A=84=E9=80=92?= =?UTF-8?q?=E5=BD=92=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 5ef23944..9ad34494 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -205,6 +205,36 @@ class Solution { go: +```go +/** +102. 二叉树的递归遍历 + */ +func levelOrder(root *TreeNode) [][]int { + arr := [][]int{} + + depth := 0 + + var order func(root *TreeNode, depth int) + + order = func(root *TreeNode, depth int) { + if root == nil { + return + } + if len(arr) == depth { + arr = append(arr, []int{}) + } + arr[depth] = append(arr[depth], root.Val) + + order(root.Left, depth+1) + order(root.Right, depth+1) + } + + order(root, depth) + + return arr +} +``` + ```go /** 102. 二叉树的层序遍历 From ba913c8909f9cc67dd674e32410c3a0dfc632910 Mon Sep 17 00:00:00 2001 From: Glaze-sauce <1471059885@qq.com> Date: Thu, 11 Aug 2022 23:54:44 +0800 Subject: [PATCH 18/18] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= =?UTF-8?q?=E7=AB=A0=E7=9A=84=200337.=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8D3?= =?UTF-8?q?=20=E7=9A=84=20Python=20=E7=89=88=E6=9C=AC=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=87=BA=E7=8E=B0=E5=B0=8F=E9=94=99=E8=AF=AF=EF=BC=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E4=BA=86=E6=88=91=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0337.打家劫舍III.md | 36 +++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index d2add232..fff8d3da 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -353,18 +353,30 @@ class Solution: # self.left = left # self.right = right class Solution: - def rob(self, root: TreeNode) -> int: - result = self.rob_tree(root) - return max(result[0], result[1]) - - def rob_tree(self, node): - if node is None: - return (0, 0) # (偷当前节点金额,不偷当前节点金额) - left = self.rob_tree(node.left) - right = self.rob_tree(node.right) - val1 = node.val + left[1] + right[1] # 偷当前节点,不能偷子节点 - val2 = max(left[0], left[1]) + max(right[0], right[1]) # 不偷当前节点,可偷可不偷子节点 - return (val1, val2) + def rob(self, root: Optional[TreeNode]) -> int: + # dp数组(dp table)以及下标的含义: + # 1. 下标为 0 记录 **不偷该节点** 所得到的的最大金钱 + # 2. 下标为 1 记录 **偷该节点** 所得到的的最大金钱 + dp = self.traversal(root) + return max(dp) + + # 要用后序遍历, 因为要通过递归函数的返回值来做下一步计算 + def traversal(self, node): + + # 递归终止条件,就是遇到了空节点,那肯定是不偷的 + if not node: + return (0, 0) + + left = self.traversal(node.left) + right = self.traversal(node.right) + + # 不偷当前节点, 偷子节点 + val_0 = max(left[0], left[1]) + max(right[0], right[1]) + + # 偷当前节点, 不偷子节点 + val_1 = node.val + left[0] + right[0] + + return (val_0, val_1) ``` ### Go