Update 回溯算法去重问题的另一种写法.md

This commit is contained in:
fw_qaq
2023-03-05 10:38:54 +08:00
committed by GitHub
parent 77aef4b18b
commit a30546d077

View File

@ -561,6 +561,49 @@ impl Solution {
} }
``` ```
**40. 组合总和 II**
```rust
use std::collections::HashSet;
impl Solution {
pub fn backtracking(
candidates: &Vec<i32>,
target: i32,
sum: i32,
path: &mut Vec<i32>,
res: &mut Vec<Vec<i32>>,
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<i32>, target: i32) -> Vec<Vec<i32>> {
let mut res = vec![];
let mut path = vec![];
candidates.sort();
Self::backtracking(&candidates, target, 0, &mut path, &mut res, 0);
res
}
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>