diff --git a/combination-sum/Real-Reason.kt b/combination-sum/Real-Reason.kt new file mode 100644 index 000000000..bce40e84f --- /dev/null +++ b/combination-sum/Real-Reason.kt @@ -0,0 +1,23 @@ +package leetcode_study + +fun combinationSum(candidates: IntArray, target: Int): List> { + val result = mutableListOf>() + val nums = ArrayDeque() + dfs(candidates, target, 0, 0, nums, result) + + return result +} + +private fun dfs(candidates: IntArray, target: Int, startIdx: Int, total: Int, nums: ArrayDeque, result: MutableList>) { + if (target < total) return + if (target == total) { + result.add(ArrayList(nums)) + return + } + for (i in startIdx..< candidates.size) { + val num = candidates[i] + nums.add(num) + dfs(candidates, target, i, total + num, nums, result) + nums.removeLast() + } +} diff --git a/product-of-array-except-self/Real-Reason.kt b/product-of-array-except-self/Real-Reason.kt new file mode 100644 index 000000000..039f93356 --- /dev/null +++ b/product-of-array-except-self/Real-Reason.kt @@ -0,0 +1,29 @@ +package leetcode_study + +fun productExceptSelf(nums: IntArray): IntArray { + // ex. nums = [1, 2, 3, 4] + val leftStartProducts = mutableListOf(1) + val rightStartProducts = mutableListOf(1) + + // mutableNums = [1, 1, 2, 3, 4] + val mutableNums = nums.toMutableList() + mutableNums.add(0, 1) + mutableNums.add(1) + + // leftStartProducts = [1, 1, 2, 6, 24, 24] + // rightStartProducts = [24, 24, 24, 12, 4, 1] + for (idx in 1..< mutableNums.size) { + val leftNum = mutableNums[idx] + val rightNum = mutableNums[mutableNums.size - 1 - idx] + + leftStartProducts.add(leftStartProducts.last() * leftNum) + rightStartProducts.add(index = 0, element = rightStartProducts.first() * rightNum) + } + + val result = mutableListOf() + for (idx in 0..mutableNums.size - 3) { + result.add(leftStartProducts[idx] * rightStartProducts[idx + 2]) + } + + return result.toIntArray() +} diff --git a/two-sum/Real-Reason.kt b/two-sum/Real-Reason.kt new file mode 100644 index 000000000..84e1952f8 --- /dev/null +++ b/two-sum/Real-Reason.kt @@ -0,0 +1,16 @@ +package leetcode_study + +class `Real-Reason` { + fun twoSum(nums: IntArray, target: Int): IntArray { + for (startIdx in 0..< nums.size - 1) { + val firstNum = nums[startIdx] + for (endIdx in startIdx + 1..< nums.size) { + val secondNum = nums[endIdx] + if (target == firstNum + secondNum) { + return intArrayOf(startIdx, endIdx) + } + } + } + throw RuntimeException("There is no solution") + } +}