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