Skip to content

Commit b7f79ad

Browse files
authored
Merge pull request #789 from Real-Reason/main
[이유진] Week3
2 parents 7682aad + 7272cda commit b7f79ad

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

combination-sum/Real-Reason.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package leetcode_study
2+
3+
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
4+
val result = mutableListOf<List<Int>>()
5+
val nums = ArrayDeque<Int>()
6+
dfs(candidates, target, 0, 0, nums, result)
7+
8+
return result
9+
}
10+
11+
private fun dfs(candidates: IntArray, target: Int, startIdx: Int, total: Int, nums: ArrayDeque<Int>, result: MutableList<List<Int>>) {
12+
if (target < total) return
13+
if (target == total) {
14+
result.add(ArrayList(nums))
15+
return
16+
}
17+
for (i in startIdx..< candidates.size) {
18+
val num = candidates[i]
19+
nums.add(num)
20+
dfs(candidates, target, i, total + num, nums, result)
21+
nums.removeLast()
22+
}
23+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package leetcode_study
2+
3+
fun productExceptSelf(nums: IntArray): IntArray {
4+
// ex. nums = [1, 2, 3, 4]
5+
val leftStartProducts = mutableListOf(1)
6+
val rightStartProducts = mutableListOf(1)
7+
8+
// mutableNums = [1, 1, 2, 3, 4]
9+
val mutableNums = nums.toMutableList()
10+
mutableNums.add(0, 1)
11+
mutableNums.add(1)
12+
13+
// leftStartProducts = [1, 1, 2, 6, 24, 24]
14+
// rightStartProducts = [24, 24, 24, 12, 4, 1]
15+
for (idx in 1..< mutableNums.size) {
16+
val leftNum = mutableNums[idx]
17+
val rightNum = mutableNums[mutableNums.size - 1 - idx]
18+
19+
leftStartProducts.add(leftStartProducts.last() * leftNum)
20+
rightStartProducts.add(index = 0, element = rightStartProducts.first() * rightNum)
21+
}
22+
23+
val result = mutableListOf<Int>()
24+
for (idx in 0..mutableNums.size - 3) {
25+
result.add(leftStartProducts[idx] * rightStartProducts[idx + 2])
26+
}
27+
28+
return result.toIntArray()
29+
}

two-sum/Real-Reason.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package leetcode_study
2+
3+
class `Real-Reason` {
4+
fun twoSum(nums: IntArray, target: Int): IntArray {
5+
for (startIdx in 0..< nums.size - 1) {
6+
val firstNum = nums[startIdx]
7+
for (endIdx in startIdx + 1..< nums.size) {
8+
val secondNum = nums[endIdx]
9+
if (target == firstNum + secondNum) {
10+
return intArrayOf(startIdx, endIdx)
11+
}
12+
}
13+
}
14+
throw RuntimeException("There is no solution")
15+
}
16+
}

0 commit comments

Comments
 (0)