0039.组合总和:Swift实现优化参数命名,添加剪枝

This commit is contained in:
bqlin
2021-12-18 20:12:46 +08:00
parent 7c4bafe9b1
commit 622b443bbe

View File

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