From 6a5c3ae29a8448c3bcf7d35f89d2c8654208a260 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sat, 11 Dec 2021 23:46:45 +0800 Subject: [PATCH] =?UTF-8?q?0039.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8C?= =?UTF-8?q?=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88=EF=BC=8C=E8=A1=A5?= =?UTF-8?q?=E5=85=85Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) 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 +} +``` + -----------------------