From 9b9980020914453b19ffad8494c6ac8fb92566ca Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+fwqaaq@users.noreply.github.com> Date: Sat, 17 Dec 2022 23:55:38 +0800 Subject: [PATCH] =?UTF-8?q?Update=200216.=E7=BB=84=E5=90=88=E6=80=BB?= =?UTF-8?q?=E5=92=8CIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0216.组合总和III.md | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) 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 - } } ```