From 57840efc1a647803b24b5c793f4622c7e150721f Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Fri, 15 Jul 2022 20:06:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200039.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C=200040.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8CI?= =?UTF-8?q?I=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0039.组合总和 0040.组合总和II Rust版本 --- problems/0039.组合总和.md | 29 +++++++++++++++++++++++++++ problems/0040.组合总和II.md | 35 +++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index 564d13ea..0f9cbc23 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -417,6 +417,35 @@ function combinationSum(candidates: number[], target: number): number[][] { }; ``` +## Rust + +```Rust +impl Solution { + pub fn backtracking(result: &mut Vec>, path: &mut Vec, candidates: &Vec, target: i32, mut sum: i32, start_index: usize) { + if sum == target { + result.push(path.to_vec()); + return; + } + for i in start_index..candidates.len() { + if sum + candidates[i] <= target { + sum += candidates[i]; + path.push(candidates[i]); + Self::backtracking(result, path, candidates, target, sum, i); + sum -= candidates[i]; + path.pop(); + } + } + } + + pub fn combination_sum(candidates: Vec, target: i32) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + Self::backtracking(&mut result, &mut path, &candidates, target, 0, 0); + result + } +} +``` + ## C ```c diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 557eb855..99577f0c 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -599,6 +599,41 @@ function combinationSum2(candidates: number[], target: number): number[][] { }; ``` +## Rust + +```Rust +impl Solution { + pub fn backtracking(result: &mut Vec>, path: &mut Vec, candidates: &Vec, target: i32, mut sum: i32, start_index: usize, used: &mut Vec) { + if sum == target { + result.push(path.to_vec()); + return; + } + for i in start_index..candidates.len() { + if sum + candidates[i] <= target { + if i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false { continue; } + sum += candidates[i]; + path.push(candidates[i]); + used[i] = true; + Self::backtracking(result, path, candidates, target, sum, i + 1, used); + used[i] = false; + sum -= candidates[i]; + path.pop(); + } + } + } + + pub fn combination_sum2(candidates: Vec, target: i32) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + let mut used: Vec = vec![false; candidates.len()]; + let mut candidates = candidates; + candidates.sort(); + Self::backtracking(&mut result, &mut path, &candidates, target, 0, 0, &mut used); + result + } +} +``` + ## C ```c