mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
0039.组合总和:Swift实现优化参数命名,添加剪枝
This commit is contained in:
@ -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() // 回溯
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user