File tree 2 files changed +63
-0
lines changed
lcof2/剑指 Offer II 082. 含有重复元素集合的组合
2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -266,6 +266,40 @@ class Comparer : IComparer<Tuple<int, int>>
266
266
}
267
267
```
268
268
269
+ #### Swift
270
+
271
+ ``` swift
272
+ class Solution {
273
+ private var ans: [[Int ]] = []
274
+ private var candidates: [Int ] = []
275
+ private var target: Int = 0
276
+
277
+ func combinationSum2 (_ candidates : [Int ], _ target : Int ) -> [[Int ]] {
278
+ self .ans = []
279
+ self .target = target
280
+ self .candidates = candidates.sorted ()
281
+ dfs (0 , 0 , [])
282
+ return ans
283
+ }
284
+
285
+ private func dfs (_ index : Int , _ sum : Int , _ current : [Int ]) {
286
+ if sum > target {
287
+ return
288
+ }
289
+ if sum == target {
290
+ ans.append (current)
291
+ return
292
+ }
293
+ for i in index..< candidates.count {
294
+ if i > index && candidates[i] == candidates[i - 1 ] {
295
+ continue
296
+ }
297
+ dfs (i + 1 , sum + candidates[i], current + [candidates[i]])
298
+ }
299
+ }
300
+ }
301
+ ```
302
+
269
303
<!-- tabs:end -->
270
304
271
305
<!-- solution:end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var ans : [ [ Int ] ] = [ ]
3
+ private var candidates : [ Int ] = [ ]
4
+ private var target : Int = 0
5
+
6
+ func combinationSum2( _ candidates: [ Int ] , _ target: Int ) -> [ [ Int ] ] {
7
+ self . ans = [ ]
8
+ self . target = target
9
+ self . candidates = candidates. sorted ( )
10
+ dfs ( 0 , 0 , [ ] )
11
+ return ans
12
+ }
13
+
14
+ private func dfs( _ index: Int , _ sum: Int , _ current: [ Int ] ) {
15
+ if sum > target {
16
+ return
17
+ }
18
+ if sum == target {
19
+ ans. append ( current)
20
+ return
21
+ }
22
+ for i in index..< candidates. count {
23
+ if i > index && candidates [ i] == candidates [ i - 1 ] {
24
+ continue
25
+ }
26
+ dfs ( i + 1 , sum + candidates[ i] , current + [ candidates [ i] ] )
27
+ }
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments