Skip to content

Commit

Permalink
Kotlin: 39. Combination Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
MaratKhakim committed Sep 18, 2022
1 parent 4253d53 commit 4aaf448
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions kotlin/39-Combination-Sum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val res = mutableListOf<List<Int>>()
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) {
list.add(nums[i])
dfs(nums, target - nums[i], i, list, res)
list.removeAt(list.size-1)
}
}
}

0 comments on commit 4aaf448

Please sign in to comment.