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] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200491.=E9=80=92=E5=A2=9E?= =?UTF-8?q?=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