diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 19fe1eb9..3b396b31 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -475,28 +475,36 @@ function combinationSum3(k: number, n: number): number[][] { ```Rust impl Solution { - fn backtracking(result: &mut Vec>, path:&mut Vec, targetSum:i32, k: i32, mut sum: i32, startIndex: i32) { + pub fn combination_sum3(k: i32, n: i32) -> Vec> { + 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>, + path: &mut Vec, + target_sum: i32, + k: i32, + sum: i32, + start_index: i32, + ) { + if sum > target_sum { + return; + } let len = path.len() as i32; if len == k { - if sum == targetSum { + if sum == target_sum { result.push(path.to_vec()); } return; } - for i in startIndex..=9 { - sum += i; + for i in start_index..=9 - (k - len) + 1 { path.push(i); - Self::backtracking(result, path, targetSum, k, sum, i+1); - sum -= i; + Self::backtrace(result, path, target_sum, k, sum + i, i + 1); path.pop(); } } - pub fn combination_sum3(k: i32, n: i32) -> Vec> { - let mut result: Vec> = Vec::new(); - let mut path: Vec = Vec::new(); - Self::backtracking(&mut result, &mut path, n, k, 0, 1); - result - } } ```