mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 回溯算法去重问题的另一种写法.md
This commit is contained in:
@ -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">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user