diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index 2265a89b..08ba64dc 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -561,6 +561,49 @@ impl Solution { } ``` +**40. 组合总和 II** + +```rust +use std::collections::HashSet; +impl Solution { + pub fn backtracking( + candidates: &Vec, + target: i32, + sum: i32, + path: &mut Vec, + res: &mut Vec>, + start_index: usize, + ) { + if sum > target { + return; + } + if sum == target { + res.push(path.clone()); + } + let mut helper_set = HashSet::new(); + for i in start_index..candidates.len() { + if sum + candidates[i] <= target { + if helper_set.contains(&candidates[i]) { + continue; + } + helper_set.insert(candidates[i]); + path.push(candidates[i]); + Self::backtracking(candidates, target, sum + candidates[i], path, res, i + 1); + path.pop(); + } + } + } + + pub fn combination_sum2(mut candidates: Vec, target: i32) -> Vec> { + let mut res = vec![]; + let mut path = vec![]; + candidates.sort(); + Self::backtracking(&candidates, target, 0, &mut path, &mut res, 0); + res + } +} +``` +