Skip to content

Commit 874a418

Browse files
authored
Merge pull request neetcode-gh#1228 from MaratKhakim/40-Comb-Sum-kt
Kotlin: 40. Combination Sum
2 parents 32fa8bc + c60dd82 commit 874a418

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

kotlin/40-Combination-Sum.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
3+
val res = mutableListOf<List<Int>>()
4+
candidates.sort()
5+
dfs(candidates, target, 0, mutableListOf<Int>(), res)
6+
return res
7+
}
8+
9+
fun dfs(nums: IntArray, target: Int, idx: Int, list: MutableList<Int>, res: MutableList<List<Int>>) {
10+
11+
if (target == 0) {
12+
res.add(ArrayList(list))
13+
return
14+
}
15+
16+
if (idx >= nums.size || target < 0)
17+
return
18+
19+
for (i in idx..nums.size-1) {
20+
if (i == idx || nums[i] != nums[i-1]) {
21+
list.add(nums[i])
22+
dfs(nums, target - nums[i], i+1, list, res)
23+
list.removeAt(list.size-1)
24+
}
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)