Skip to content

Commit 5e112c3

Browse files
committed
feat: Add solution for LeetCode problem 39
1 parent e113d55 commit 5e112c3

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

combination-sum/WhiteHyun.swift

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,30 @@
77
//
88

99
class Solution {
10-
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
11-
10+
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
11+
let sortedCandidates = candidates.sorted()
12+
var answer: [[Int]] = []
13+
14+
func backtrack(_ sum: Int, _ start: Int, _ current: [Int]) {
15+
if sum == target {
16+
answer.append(current)
17+
return
18+
}
19+
20+
if sum > target {
21+
return
22+
}
23+
24+
for i in start ..< sortedCandidates.count {
25+
let newSum = sum + sortedCandidates[i]
26+
if newSum > target {
27+
break
28+
}
29+
backtrack(newSum, i, current + [sortedCandidates[i]])
30+
}
1231
}
32+
33+
backtrack(0, 0, [])
34+
return answer
35+
}
1336
}

0 commit comments

Comments
 (0)