From 2fc73adfebdee3787ed1081804e904ae674449c3 Mon Sep 17 00:00:00 2001 From: sjjeong Date: Mon, 12 Oct 2020 20:21:42 +0900 Subject: [PATCH] CombinationSum --- sjjeong/CombinationSum.kt | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sjjeong/CombinationSum.kt diff --git a/sjjeong/CombinationSum.kt b/sjjeong/CombinationSum.kt new file mode 100644 index 0000000..dfbf9e5 --- /dev/null +++ b/sjjeong/CombinationSum.kt @@ -0,0 +1,42 @@ +class Solution { + fun combinationSum(candidates: IntArray, target: Int): List> { + return generateResult(candidates.toList(), target).filter { it.sum() == target } + } + + private fun generateResult(candidates: List, target: Int): List> { + return candidates.takeIf { it.isNotEmpty() }?.run { + flatMapIndexed { index: Int, num: Int -> + when { + target < num -> { + listOf(listOf()) + } + target == num -> { + listOf(listOf(target)) + } + else -> { + generateResult(candidates.drop(index), target - num).map { + it.toMutableList() + .apply { + add(0, num) + } + } + } + } + } + }?: listOf(listOf()) + } + + private inline fun Iterable.flatMapIndexed(transform: (index: Int, T) -> Iterable): List { + return flatMapIndexedTo(ArrayList(), transform) + } + + private inline fun > Iterable.flatMapIndexedTo(destination: C, transform: (index: Int, T) -> Iterable): C { + var index = 0 + for (element in this) { + val list = transform(index++, element) + destination.addAll(list) + } + return destination + } + +}