-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathjdalma.kt
46 lines (40 loc) ยท 1.72 KB
/
jdalma.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `combination-sum` {
/**
* ํ๋ณด์๋ฅผ ์ค๋ณต์ผ๋ก ์ฌ์ฉํ ์ ์๊ธฐ์ 0๋ถํฐ ํ๋ณด์๋ค์ ๋์ ํ๋ฉด์ target๋ณด๋ค ํฌ๋ฉด ํ์ถํ๋ ๋ฐฉ์์ด๋ค.
* ๋ง์ฝ target๊ณผ ๋์ผํ๋ค๋ฉด ๋์ ํ ๋ ์ฌ์ฉ๋ ํ๋ณด์๋ค์ numbers์ ์ ์ฅํด๋๊ธฐ์ ๊ฒฐ๊ณผ์ ๋ณต์ฌํ๋ค.
* ์๊ฐ๋ณต์ก๋: O(n^t), ๊ณต๊ฐ๋ณต์ก๋: O(t)
*/
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
fun backtracking(candidates: IntArray, target: Int, result: MutableList<List<Int>>, numbers: MutableList<Int>, start: Int, total: Int) {
if (total > target) return
else if (total == target) {
result.add(numbers.toList())
} else {
(start until candidates.size).forEach {
numbers.add(candidates[it])
backtracking(candidates, target, result, numbers, it, total + candidates[it])
numbers.removeLast()
}
}
}
val result = mutableListOf<List<Int>>()
backtracking(candidates, target, result, mutableListOf(), 0, 0)
return result
}
@Test
fun `์
๋ ฅ๋ฐ์ ์ ์ ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํ์ฌ ๋ชฉํฏ๊ฐ์ ๋ง๋ค์ด๋ผ ์ ์๋ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ค`() {
combinationSum(intArrayOf(2,3,6,7), 7) shouldBe listOf(
listOf(2,2,3),
listOf(7)
)
combinationSum(intArrayOf(2,3,5), 8) shouldBe listOf(
listOf(2,2,2,2),
listOf(2,3,3),
listOf(3,5)
)
combinationSum(intArrayOf(2), 1) shouldBe listOf()
}
}