Skip to content

Commit 94e2d3a

Browse files
authored
feat: add swift implementation to lcof2 problem: No.080 (doocs#3459)
1 parent 20b0f51 commit 94e2d3a

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

lcof2/剑指 Offer II 080. 含有 k 个元素的组合/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,35 @@ func dfs(i, n, k int, t []int, res *[][]int) {
151151
}
152152
```
153153

154+
#### Swift
155+
156+
```swift
157+
class Solution {
158+
func combine(_ n: Int, _ k: Int) -> [[Int]] {
159+
var res = [[Int]]()
160+
dfs(1, n, k, [], &res)
161+
return res
162+
}
163+
164+
private func dfs(_ start: Int, _ n: Int, _ k: Int, _ current: [Int], _ res: inout [[Int]]) {
165+
if current.count == k {
166+
res.append(current)
167+
return
168+
}
169+
170+
if start > n {
171+
return
172+
}
173+
174+
for i in start...n {
175+
var newCurrent = current
176+
newCurrent.append(i)
177+
dfs(i + 1, n, k, newCurrent, &res)
178+
}
179+
}
180+
}
181+
```
182+
154183
<!-- tabs:end -->
155184

156185
<!-- solution:end -->
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
func combine(_ n: Int, _ k: Int) -> [[Int]] {
3+
var res = [[Int]]()
4+
dfs(1, n, k, [], &res)
5+
return res
6+
}
7+
8+
private func dfs(_ start: Int, _ n: Int, _ k: Int, _ current: [Int], _ res: inout [[Int]]) {
9+
if current.count == k {
10+
res.append(current)
11+
return
12+
}
13+
14+
if start > n {
15+
return
16+
}
17+
18+
for i in start...n {
19+
var newCurrent = current
20+
newCurrent.append(i)
21+
dfs(i + 1, n, k, newCurrent, &res)
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)