From a30546d0777b41eb415d056f6f15dd4cc88e878e Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Sun, 5 Mar 2023 10:38:54 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E5=9B=9E=E6=BA=AF=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E5=8E=BB=E9=87=8D=E9=97=AE=E9=A2=98=E7=9A=84=E5=8F=A6=E4=B8=80?= =?UTF-8?q?=E7=A7=8D=E5=86=99=E6=B3=95.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...溯算法去重问题的另一种写法.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) 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 + } +} +``` +