mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
0039.组合总和:优化排版,补充Swift版本
This commit is contained in:
@ -365,7 +365,7 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int)
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## JavaScript:
|
## JavaScript
|
||||||
|
|
||||||
```js
|
```js
|
||||||
var combinationSum = function(candidates, target) {
|
var combinationSum = function(candidates, target) {
|
||||||
@ -447,5 +447,32 @@ int** combinationSum(int* candidates, int candidatesSize, int target, int* retur
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Swift
|
||||||
|
|
||||||
|
```swift
|
||||||
|
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
|
||||||
|
var result = [[Int]]()
|
||||||
|
var path = [Int]()
|
||||||
|
func backtracking(sum: Int, startIndex: Int) {
|
||||||
|
// 终止条件
|
||||||
|
if sum > target { return }
|
||||||
|
if sum == target {
|
||||||
|
result.append(path)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let end = candidates.count
|
||||||
|
guard startIndex < end else { return }
|
||||||
|
for i in startIndex ..< end {
|
||||||
|
path.append(candidates[i]) // 处理
|
||||||
|
backtracking(sum: sum + candidates[i], startIndex: i) // sum这里用新变量完成回溯,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>
|
||||||
|
Reference in New Issue
Block a user