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