mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
0216.组合总和III:优化排版,补充Swift版本
This commit is contained in:
@ -57,7 +57,7 @@
|
||||
|
||||
至于为什么取名为path?从上面树形结构中,可以看出,结果其实就是一条根节点到叶子节点的路径。
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<vector<int>> result; // 存放结果集
|
||||
vector<int> path; // 符合条件的结果
|
||||
```
|
||||
@ -71,7 +71,7 @@ vector<int> path; // 符合条件的结果
|
||||
|
||||
所以代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<vector<int>> result;
|
||||
vector<int> 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
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<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