Skip to content

Commit d38cb68

Browse files
committed
Create 0040-combination-sum-ii.swift
1 parent 0beb8f5 commit d38cb68

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

swift/0040-combination-sum-ii.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {
3+
var candidates = candidates.sorted()
4+
var res = [[Int]]()
5+
var cur = [Int]()
6+
var total = 0
7+
8+
func dfs(_ i: Int) {
9+
var i = i
10+
if total == target {
11+
res.append(cur)
12+
return
13+
}
14+
if total > target || i == candidates.count {
15+
return
16+
}
17+
18+
cur.append(candidates[i])
19+
total += candidates[i]
20+
dfs(i + 1)
21+
cur.popLast()
22+
total -= candidates[i]
23+
while i + 1 < candidates.count && candidates[i] == candidates[i + 1] {
24+
i += 1
25+
}
26+
dfs(i + 1)
27+
}
28+
29+
dfs(0)
30+
31+
return res
32+
}
33+
}

0 commit comments

Comments
 (0)