Skip to content

Commit dafbd2f

Browse files
author
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ
committed
combination sum
1 parent 7740c13 commit dafbd2f

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package leetcode_study
2+
3+
/*
4+
* target์„ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์กฐํ•ฉ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ
5+
* ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•ด ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•œ ํ›„ ๊ตฌํ•œ ๊ฒฐ๊ณผ๊ฐ’์—์„œ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ ํ•ด๊ฒฐ
6+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(2^(target size))
7+
* -> target ๊ฐ’์„ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์ฐพ๋Š” ๊ณผ์ •
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(2^(target size))
9+
* -> removeDuplicates๋Š” ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋จ. ์ค‘๋ณต์„ ์ œ์™ธํ•˜๋Š” ๊ณผ์ •์—์„œ O(2^(target size))๊ฐœ์˜ ๋ฆฌ์ŠคํŠธ ์‚ฌ์šฉ
10+
* */
11+
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
12+
val result = mutableListOf<List<Int>>()
13+
14+
fun combination(target: Int, current: List<Int>) {
15+
if (target == 0) {
16+
result.add(current)
17+
return
18+
}
19+
if (target < 0) return
20+
21+
for (candidate in candidates) {
22+
combination(target - candidate, current + candidate)
23+
}
24+
}
25+
combination(target, emptyList())
26+
27+
val removeDuplicates = mutableSetOf<List<Int>>()
28+
29+
for (i in result) {
30+
val temp = i.sorted()
31+
removeDuplicates.add(temp)
32+
}
33+
return removeDuplicates.toList()
34+
}
35+
36+
/*
37+
* ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ๋•Œ, ์žฌ๊ท€ ์ž‘์„ฑ ์‹œ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ ํ•ด๊ฒฐ
38+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(2^(target size))
39+
* -> target ๊ฐ’์„ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์ฐพ๋Š” ๊ณผ์ •
40+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(target size)
41+
* -> ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ณต๊ฐ„์ด target ๊ฐ’์— ๋น„๋ก€ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ์žฌ๊ท€ ๊นŠ์ด๋Š” O(target size)
42+
* */
43+
fun combinationSumUsingBackTracking(candidates: IntArray, target: Int): List<List<Int>> {
44+
val result = mutableListOf<List<Int>>()
45+
46+
fun combination(target: Int, current: MutableList<Int>, start: Int) {
47+
if (target == 0) {
48+
result.add(current.toList()) // ํ˜„์žฌ ์กฐํ•ฉ์„ ๊ฒฐ๊ณผ์— ์ถ”๊ฐ€
49+
return
50+
}
51+
if (target < 0) return
52+
53+
for (i in start until candidates.size) {
54+
current.add(candidates[i]) // ํ›„๋ณด ์ถ”๊ฐ€
55+
combination(target - candidates[i], current, i) // ํ˜„์žฌ ํ›„๋ณด๋ฅผ ๋‹ค์‹œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ
56+
current.removeAt(current.lastIndex) // ๋ฐฑํŠธ๋ž˜ํ‚น
57+
}
58+
}
59+
60+
combination(target, mutableListOf(), 0)
61+
return result
62+
}

0 commit comments

Comments
ย (0)