From f702f0482d678ef2c989d477157b0b6542852348 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sat, 11 Dec 2021 18:18:45 +0800 Subject: [PATCH] =?UTF-8?q?0216.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8CIII?= =?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/0216.组合总和III.md | 45 +++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index fa2ce37f..76d31098 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -57,7 +57,7 @@ 至于为什么取名为path?从上面树形结构中,可以看出,结果其实就是一条根节点到叶子节点的路径。 -``` +```cpp vector> result; // 存放结果集 vector path; // 符合条件的结果 ``` @@ -71,7 +71,7 @@ vector path; // 符合条件的结果 所以代码如下: -``` +```cpp vector> result; vector path; void backtracking(int targetSum, int k, int sum, int startIndex) @@ -168,7 +168,7 @@ public: 那么剪枝的地方一定是在递归终止的地方剪,剪枝代码如下: -``` +```cpp if (sum > targetSum) { // 剪枝操作 return; } @@ -319,7 +319,7 @@ class Solution: return res ``` -## Go: +## Go 回溯+减枝 @@ -351,7 +351,7 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){ } ``` -## javaScript: +## javaScript ```js // 等差数列 @@ -390,7 +390,8 @@ var combinationSum3 = function(k, n) { }; ``` -C: +## C + ```c int* path; int pathTop; @@ -448,5 +449,37 @@ int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes){ } ``` +## Swift + +```swift +func combinationSum3(_ k: Int, _ n: Int) -> [[Int]] { + var result = [[Int]]() + var path = [Int]() + func backtracking(targetSum: Int, k: Int, sum: Int, startIndex: Int) { + // 剪枝 + if sum > targetSum { return } + // 终止条件 + if path.count == k { + if sum == targetSum { + result.append(path) + } + return + } + + // 单层逻辑 + let endIndex = 9 + guard startIndex <= endIndex else { return } + for i in startIndex ... endIndex { + path.append(i) // 处理 + backtracking(targetSum: targetSum, k: k, sum: sum + i, startIndex: i + 1) + path.removeLast() // 回溯 + } + } + + backtracking(targetSum: n, k: k, sum: 0, startIndex: 1) + return result +} +``` + -----------------------