-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathgmlwls96.kt
50 lines (46 loc) · 1.51 KB
/
gmlwls96.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
class Solution {
// 시간 : O(c^t), 공간 : O(t)
// 알고리즘 : dfs
val answerList = mutableSetOf<List<Int>>()
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
candidates.sort()
combination(
candidates = candidates,
target = target,
current = 0,
currentList = listOf()
)
return answerList.toList()
}
private fun combination(
candidates: IntArray,
target: Int,
current: Int,
currentList: List<Int>
) {
candidates.forEach { // candidates를 한개씩 꺼내
val sum = current + it // 현재값을 더했을때
when {
sum == target -> { // sum이 target과 동일한 값이면 answer 에 추가.
answerList.add(
currentList.toMutableList().apply {
add(it)
sort()
}
)
}
sum < target -> { // sum이 모자르면 다른 조합을 찾기 위해 재귀 호출.
combination(
candidates = candidates,
target = target,
current = sum,
currentList = currentList.toMutableList().apply {
add(it)
}
)
}
else -> return
}
}
}
}