mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
0216.组合总和III:更新Swift实现
This commit is contained in:
@ -452,14 +452,14 @@ int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes){
|
|||||||
## Swift
|
## Swift
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
func combinationSum3(_ k: Int, _ n: Int) -> [[Int]] {
|
func combinationSum3(_ count: Int, _ targetSum: Int) -> [[Int]] {
|
||||||
var result = [[Int]]()
|
var result = [[Int]]()
|
||||||
var path = [Int]()
|
var path = [Int]()
|
||||||
func backtracking(targetSum: Int, k: Int, sum: Int, startIndex: Int) {
|
func backtracking(sum: Int, startIndex: Int) {
|
||||||
// 剪枝
|
// 剪枝
|
||||||
if sum > targetSum { return }
|
if sum > targetSum { return }
|
||||||
// 终止条件
|
// 终止条件
|
||||||
if path.count == k {
|
if path.count == count {
|
||||||
if sum == targetSum {
|
if sum == targetSum {
|
||||||
result.append(path)
|
result.append(path)
|
||||||
}
|
}
|
||||||
@ -471,12 +471,12 @@ func combinationSum3(_ k: Int, _ n: Int) -> [[Int]] {
|
|||||||
guard startIndex <= endIndex else { return }
|
guard startIndex <= endIndex else { return }
|
||||||
for i in startIndex ... endIndex {
|
for i in startIndex ... endIndex {
|
||||||
path.append(i) // 处理
|
path.append(i) // 处理
|
||||||
backtracking(targetSum: targetSum, k: k, sum: sum + i, startIndex: i + 1)
|
backtracking(sum: sum + i, startIndex: i + 1)
|
||||||
path.removeLast() // 回溯
|
path.removeLast() // 回溯
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
backtracking(targetSum: n, k: k, sum: 0, startIndex: 1)
|
backtracking(sum: 0, startIndex: 1)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user