Created
October 2, 2019 07:13
-
-
Save voquanghoa/a1c4de32fc0c38484f825fa279888cfd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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