Skip to content

Commit 1459cc7

Browse files
authored
feat: add swift implementation to lcof2 problem: No.081 (#3460)
1 parent 94e2d3a commit 1459cc7

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

lcof2/剑指 Offer II 081. 允许重复选择元素的组合/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,38 @@ public class Solution
258258
}
259259
```
260260

261+
#### Swift
262+
263+
```swift
264+
class Solution {
265+
private var ans: [[Int]] = []
266+
private var target: Int = 0
267+
private var candidates: [Int] = []
268+
269+
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
270+
self.ans = []
271+
self.target = target
272+
self.candidates = candidates
273+
dfs(0, 0, [])
274+
return ans
275+
}
276+
277+
private func dfs(_ sum: Int, _ index: Int, _ current: [Int]) {
278+
if sum == target {
279+
ans.append(current)
280+
return
281+
}
282+
if sum > target {
283+
return
284+
}
285+
for i in index..<candidates.count {
286+
let candidate = candidates[i]
287+
dfs(sum + candidate, i, current + [candidate])
288+
}
289+
}
290+
}
291+
```
292+
261293
<!-- tabs:end -->
262294

263295
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
private var ans: [[Int]] = []
3+
private var target: Int = 0
4+
private var candidates: [Int] = []
5+
6+
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
7+
self.ans = []
8+
self.target = target
9+
self.candidates = candidates
10+
dfs(0, 0, [])
11+
return ans
12+
}
13+
14+
private func dfs(_ sum: Int, _ index: Int, _ current: [Int]) {
15+
if sum == target {
16+
ans.append(current)
17+
return
18+
}
19+
if sum > target {
20+
return
21+
}
22+
for i in index..<candidates.count {
23+
let candidate = candidates[i]
24+
dfs(sum + candidate, i, current + [candidate])
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)