diff --git a/namjackson/CombinationSum.kt b/namjackson/CombinationSum.kt new file mode 100644 index 0000000..6f08b94 --- /dev/null +++ b/namjackson/CombinationSum.kt @@ -0,0 +1,29 @@ +class Solution { + fun combinationSum(candidates: IntArray, target: Int): List> { + val resultList = mutableListOf>() + search(candidates.sortedArrayDescending(), target, intArrayOf(), resultList) + return resultList.distinct() + } + + private fun search( + candidates: IntArray, + target: Int, + sumArray: IntArray, + resultList: MutableList> + ) { + val sum = sumArray.sum() + candidates.forEach { num -> + val gap = target - (sum + num) + when { + (gap == 0) -> { + val list = sumArray.toMutableList().also { it.add(num) } + resultList.add(list.sorted()) + } + (gap > 0) -> { + val list = sumArray.toMutableList().also { it.add(num) } + search(candidates, target, list.toIntArray(), resultList) + } + } + } + } +} \ No newline at end of file