Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1228 from MaratKhakim/40-Comb-Sum-kt
Browse files Browse the repository at this point in the history
Kotlin: 40. Combination Sum
  • Loading branch information
Ahmad-A0 authored Oct 8, 2022
2 parents 32fa8bc + c60dd82 commit 874a418
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions kotlin/40-Combination-Sum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
val res = mutableListOf<List<Int>>()
candidates.sort()
dfs(candidates, target, 0, mutableListOf<Int>(), res)
return res
}

fun dfs(nums: IntArray, target: Int, idx: Int, list: MutableList<Int>, res: MutableList<List<Int>>) {

if (target == 0) {
res.add(ArrayList(list))
return
}

if (idx >= nums.size || target < 0)
return

for (i in idx..nums.size-1) {
if (i == idx || nums[i] != nums[i-1]) {
list.add(nums[i])
dfs(nums, target - nums[i], i+1, list, res)
list.removeAt(list.size-1)
}
}
}
}

0 comments on commit 874a418

Please sign in to comment.