mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1823 from fwqaaq/patch-29
Update 0216.组合总和III.md about rust 优化
This commit is contained in:
@ -479,28 +479,36 @@ function combinationSum3(k: number, n: number): number[][] {
|
|||||||
|
|
||||||
```Rust
|
```Rust
|
||||||
impl Solution {
|
impl Solution {
|
||||||
fn backtracking(result: &mut Vec<Vec<i32>>, path:&mut Vec<i32>, targetSum:i32, k: i32, mut sum: i32, startIndex: i32) {
|
pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> {
|
||||||
|
let mut result = vec![];
|
||||||
|
let mut path = vec![];
|
||||||
|
Self::backtrace(&mut result, &mut path, n, k, 0, 1);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
pub fn backtrace(
|
||||||
|
result: &mut Vec<Vec<i32>>,
|
||||||
|
path: &mut Vec<i32>,
|
||||||
|
target_sum: i32,
|
||||||
|
k: i32,
|
||||||
|
sum: i32,
|
||||||
|
start_index: i32,
|
||||||
|
) {
|
||||||
|
if sum > target_sum {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let len = path.len() as i32;
|
let len = path.len() as i32;
|
||||||
if len == k {
|
if len == k {
|
||||||
if sum == targetSum {
|
if sum == target_sum {
|
||||||
result.push(path.to_vec());
|
result.push(path.to_vec());
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for i in startIndex..=9 {
|
for i in start_index..=9 - (k - len) + 1 {
|
||||||
sum += i;
|
|
||||||
path.push(i);
|
path.push(i);
|
||||||
Self::backtracking(result, path, targetSum, k, sum, i+1);
|
Self::backtrace(result, path, target_sum, k, sum + i, i + 1);
|
||||||
sum -= i;
|
|
||||||
path.pop();
|
path.pop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn combination_sum3(k: i32, n: 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, n, k, 0, 1);
|
|
||||||
result
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user