0040.组合总和II:优化排版,补充Swift版本

This commit is contained in:
bqlin
2021-12-12 10:28:21 +08:00
parent 6a5c3ae29a
commit 9a577c7b25

View File

@ -381,7 +381,7 @@ class Solution:
sum_ -= candidates[i] # 回溯为了下一轮for loop sum_ -= candidates[i] # 回溯为了下一轮for loop
``` ```
## Go ## Go
主要在于如何在回溯中去重 主要在于如何在回溯中去重
```go ```go
@ -424,7 +424,7 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,
} }
``` ```
## javaScript ## javaScript
```js ```js
/** /**
@ -550,5 +550,37 @@ int** combinationSum2(int* candidates, int candidatesSize, int target, int* retu
} }
``` ```
## Swift
```swift
func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {
// 为了方便去重复,先对集合排序
let candidates = candidates.sorted()
var result = [[Int]]()
var path = [Int]()
func backtracking(sum: Int, startIndex: Int) {
// 终止条件
if sum == target {
result.append(path)
return
}
let end = candidates.count
guard startIndex < end else { return }
for i in startIndex ..< end {
if i > startIndex, candidates[i] == candidates[i - 1] { continue } // 去重复
let sum = sum + candidates[i] // 使用局部变量隐藏回溯
if sum > target { continue } // 剪枝
path.append(candidates[i]) // 处理
backtracking(sum: sum, startIndex: i + 1) // i+1避免重复访问
path.removeLast() // 回溯
}
}
backtracking(sum: 0, startIndex: 0)
return result
}
```
----------------------- -----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div> <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>