Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ca46b52

Browse files
feat: add swift implementation to lcof2 problem: No.082 (#3461)
1 parent 1459cc7 commit ca46b52

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

‎lcof2/剑指 Offer II 082. 含有重复元素集合的组合/README.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,40 @@ class Comparer : IComparer<Tuple<int, int>>
266266
}
267267
```
268268

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+
269303
<!-- tabs:end -->
270304

271305
<!-- solution:end -->
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /