Merge pull request #1523 from cezarbbb/Backtracking

添加 0039.组合总和 0040.组合总和II Rust版本
This commit is contained in:
程序员Carl
2022-08-03 09:43:14 +08:00
committed by GitHub
2 changed files with 64 additions and 0 deletions

View File

@ -417,6 +417,35 @@ function combinationSum(candidates: number[], target: number): number[][] {
};
```
## Rust
```Rust
impl Solution {
pub fn backtracking(result: &mut Vec<Vec<i32>>, path: &mut Vec<i32>, candidates: &Vec<i32>, 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<i32>, target: i32) -> Vec<Vec<i32>> {
let mut result: Vec<Vec<i32>> = Vec::new();
let mut path: Vec<i32> = Vec::new();
Self::backtracking(&mut result, &mut path, &candidates, target, 0, 0);
result
}
}
```
## C
```c

View File

@ -599,6 +599,41 @@ function combinationSum2(candidates: number[], target: number): number[][] {
};
```
## Rust
```Rust
impl Solution {
pub fn backtracking(result: &mut Vec<Vec<i32>>, path: &mut Vec<i32>, candidates: &Vec<i32>, target: i32, mut sum: i32, start_index: usize, used: &mut Vec<bool>) {
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<i32>, target: i32) -> Vec<Vec<i32>> {
let mut result: Vec<Vec<i32>> = Vec::new();
let mut path: Vec<i32> = Vec::new();
let mut used: Vec<bool> = 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