diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index c2c7530d..81be41fd 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -365,7 +365,7 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int) } ``` -## JavaScript: +## JavaScript ```js 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 +} +``` + -----------------------