diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index e78f2e2d..0f8fe4f6 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -455,7 +455,6 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { var path = [Int]() func backtracking(sum: Int, startIndex: Int) { // 终止条件 - if sum > target { return } if sum == target { result.append(path) return @@ -464,8 +463,11 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { let end = candidates.count guard startIndex < end else { return } for i in startIndex ..< end { + let sum = sum + candidates[i] // 使用局部变量隐藏回溯 + if sum > target { continue } // 剪枝 + path.append(candidates[i]) // 处理 - backtracking(sum: sum + candidates[i], startIndex: i) // sum这里用新变量完成回溯,i不用+1以重复访问 + backtracking(sum: sum, startIndex: i) // i不用+1以重复访问 path.removeLast() // 回溯 } }