Skip to content

Instantly share code, notes, and snippets.

@voquanghoa
Created October 2, 2019 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voquanghoa/a1c4de32fc0c38484f825fa279888cfd to your computer and use it in GitHub Desktop.
Save voquanghoa/a1c4de32fc0c38484f825fa279888cfd to your computer and use it in GitHub Desktop.
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val counts = IntArray(candidates.size){0}
val result = mutableListOf<List<Int>>()
fun gen(i: Int, newTarget: Int){
if(newTarget < 0){
return
}
if(newTarget == 0){
result.add((0 until i).flatMap {x -> (0 until counts[x]).map { candidates[x] } })
return
}
if(i >= candidates.size){
return
}
var current = newTarget
counts[i] = 0
gen(i+1, current)
while (current > 0){
counts[i] ++
current -= candidates[i]
gen(i+1, current)
}
}
gen(0, target)
result.reverse()
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment