mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
0077.组合:优化排版,补充Swift版本
This commit is contained in:
@ -109,7 +109,7 @@ for (int i = 1; i <= n; i++) {
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<vector<int>> result; // 存放符合条件结果的集合
|
||||
vector<int> path; // 用来存放符合条件结果
|
||||
```
|
||||
@ -132,7 +132,7 @@ vector<int> path; // 用来存放符合条件结果
|
||||
|
||||
那么整体代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<vector<int>> result; // 存放符合条件结果的集合
|
||||
vector<int> path; // 用来存放符合条件单一结果
|
||||
void backtracking(int n, int k, int startIndex)
|
||||
@ -152,7 +152,7 @@ path这个数组的大小如果达到k,说明我们找到了一个子集大小
|
||||
|
||||
所以终止条件代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
if (path.size() == k) {
|
||||
result.push_back(path);
|
||||
return;
|
||||
@ -248,7 +248,7 @@ void backtracking(参数) {
|
||||
|
||||
在遍历的过程中有如下代码:
|
||||
|
||||
```
|
||||
```cpp
|
||||
for (int i = startIndex; i <= n; i++) {
|
||||
path.push_back(i);
|
||||
backtracking(n, k, i + 1);
|
||||
@ -411,7 +411,7 @@ class Solution:
|
||||
path.pop()
|
||||
backtrack(n, k, 1)
|
||||
return res
|
||||
```
|
||||
```
|
||||
|
||||
剪枝:
|
||||
```python3
|
||||
@ -454,7 +454,7 @@ const combineHelper = (n, k, startIndex) => {
|
||||
path.pop()
|
||||
}
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
|
||||
|
||||
@ -621,5 +621,35 @@ int** combine(int n, int k, int* returnSize, int** returnColumnSizes){
|
||||
}
|
||||
```
|
||||
|
||||
## Swift
|
||||
|
||||
```swift
|
||||
func combine(_ n: Int, _ k: Int) -> [[Int]] {
|
||||
var path = [Int]()
|
||||
var result = [[Int]]()
|
||||
func backtracking(_ n: Int, _ k: Int, _ startIndex: Int) {
|
||||
// 结束条件,并收集结果
|
||||
if path.count == k {
|
||||
result.append(path)
|
||||
return
|
||||
}
|
||||
|
||||
// 单层逻辑
|
||||
// let end = n
|
||||
// 剪枝优化
|
||||
let end = n - (k - path.count) + 1
|
||||
guard startIndex <= end else { return }
|
||||
for i in startIndex ... end {
|
||||
path.append(i) // 处理结点
|
||||
backtracking(n, k, i + 1) // 递归
|
||||
path.removeLast() // 回溯
|
||||
}
|
||||
}
|
||||
|
||||
backtracking(n, k, 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