Skip to content

Commit

Permalink
Kotlin: 40. Combination Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
MaratKhakim committed Oct 3, 2022
1 parent c50d6fa commit c60dd82
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 c60dd82

Please sign in to comment.