-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathEcoFriendlyAppleSu.kt
62 lines (53 loc) ยท 2.27 KB
/
EcoFriendlyAppleSu.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package leetcode_study
/*
* ์ฃผ์ด์ง ๋ฐฐ์ด๋ก ๋ง๋ค ์ ์๋ ๊ฐ(target)์ ๊ตฌ์ฑํ ์ ์๋ ๋ชจ๋ ์กฐํฉ์ ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
* ์ฌ๊ท๋ฅผ ์ฌ์ฉํด ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๊ตฌํ ํ ๊ตฌํ ๊ฒฐ๊ณผ๊ฐ์์ ์ค๋ณต์ ์ ๊ฑฐํ๋ ๋ฐฉ์์ผ๋ก ๋ฌธ์ ํด๊ฒฐ
* ์๊ฐ ๋ณต์ก๋: O(2^n)
* -> target ๊ฐ์ 0์ผ๋ก ๋ง๋ค๊ธฐ ์ํด ๊ฐ๋ฅํ ๋ชจ๋ ์กฐํฉ์ ์ฐพ๋ ๊ณผ์
* ๊ณต๊ฐ ๋ณต์ก๋: O(2^n)
* -> removeDuplicates๋ ์ค๋ณต์ ์ ๊ฑฐํ๊ณ ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ๋ ๋ฐ ์ฌ์ฉ๋จ. ์ค๋ณต์ ์ ์ธํ๋ ๊ณผ์ ์์ O(2^n)๊ฐ์ ๋ฆฌ์คํธ ์ฌ์ฉ
* */
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
fun combination(target: Int, current: List<Int>) {
if (target == 0) {
result.add(current)
return
}
if (target < 0) return
for (candidate in candidates) {
combination(target - candidate, current + candidate)
}
}
combination(target, emptyList())
val removeDuplicates = mutableSetOf<List<Int>>()
for (i in result) {
val temp = i.sorted()
removeDuplicates.add(temp)
}
return removeDuplicates.toList()
}
/*
* ์ฌ๊ท๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ๋, ์ฌ๊ท ์์ฑ ์ ์ค๋ณต์ ์ ๊ฑฐํ๋ ๋ฐฉ์์ผ๋ก ๋ฌธ์ ํด๊ฒฐ
* ์๊ฐ ๋ณต์ก๋: O(2^n)
* -> target ๊ฐ์ 0์ผ๋ก ๋ง๋ค๊ธฐ ์ํด ๊ฐ๋ฅํ ๋ชจ๋ ์กฐํฉ์ ์ฐพ๋ ๊ณผ์
* ๊ณต๊ฐ ๋ณต์ก๋: O(n)
* -> ์ฌ๊ท ํธ์ถ ์คํ์์ ์ฌ์ฉํ๋ ๊ณต๊ฐ์ด target ๊ฐ์ ๋น๋กํ๊ธฐ ๋๋ฌธ์, ์ฌ๊ท ๊น์ด๋ O(n)
* */
fun combinationSumUsingBackTracking(candidates: IntArray, target: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
fun combination(target: Int, current: MutableList<Int>, start: Int) {
if (target == 0) {
result.add(current.toList()) // ํ์ฌ ์กฐํฉ์ ๊ฒฐ๊ณผ์ ์ถ๊ฐ
return
}
if (target < 0) return
for (i in start until candidates.size) {
current.add(candidates[i]) // ํ๋ณด ์ถ๊ฐ
combination(target - candidates[i], current, i) // ํ์ฌ ํ๋ณด๋ฅผ ๋ค์ ์ฌ์ฉํ ์ ์์
current.removeAt(current.lastIndex) // ๋ฐฑํธ๋ํน
}
}
combination(target, mutableListOf(), 0)
return result
}