Skip to content

Commit a8e6f6f

Browse files
Merge pull request neetcode-gh#2936 from neetcode-gh/0039-combination-sum
Swift: 39. Combination Sum
2 parents eff3b93 + 85620d7 commit a8e6f6f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

swift/0039-combination-sum.swift

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
3+
var result: [[Int]] = []
4+
var currentComb: [Int] = []
5+
func dfs(_ index: Int, _ remaining: Int) {
6+
guard index < candidates.count else { return }
7+
guard remaining >= 0 else {
8+
return
9+
}
10+
if remaining == 0 {
11+
result.append(currentComb)
12+
return
13+
}
14+
for i in index..<candidates.count {
15+
currentComb.append(candidates[i])
16+
dfs(i, remaining - candidates[i])
17+
currentComb.removeLast()
18+
}
19+
}
20+
dfs(0, target)
21+
return result
22+
}
23+
}

0 commit comments

Comments
 (0)