File tree 2 files changed +59
-0
lines changed
lcof2/剑指 Offer II 081. 允许重复选择元素的组合
2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -258,6 +258,38 @@ public class Solution
258
258
}
259
259
```
260
260
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
+
261
293
<!-- tabs:end -->
262
294
263
295
<!-- solution:end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments