Skip to content

Commit

Permalink
0039.组合总和:Swift实现优化参数命名,添加剪枝
Browse files Browse the repository at this point in the history
  • Loading branch information
bqlin committed Dec 23, 2021
1 parent 7c4bafe commit 622b443
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions problems/0039.组合总和.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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() // 回溯
}
}
Expand Down

0 comments on commit 622b443

Please sign in to comment.