mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
0040.组合总和II:优化排版,补充Swift版本
This commit is contained in:
@ -381,7 +381,7 @@ class Solution:
|
||||
sum_ -= candidates[i] # 回溯,为了下一轮for loop
|
||||
```
|
||||
|
||||
## Go:
|
||||
## Go
|
||||
主要在于如何在回溯中去重
|
||||
|
||||
```go
|
||||
@ -424,7 +424,7 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,
|
||||
}
|
||||
```
|
||||
|
||||
## javaScript:
|
||||
## javaScript
|
||||
|
||||
```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>
|
||||
|
Reference in New Issue
Block a user