Skip to content

Commit

Permalink
combination sum
Browse files Browse the repository at this point in the history
  • Loading branch information
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ committed Jan 2, 2025
1 parent 7740c13 commit dafbd2f
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions combination-sum/EcoFriendlyAppleSu.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package leetcode_study

/*
* target์„ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์กฐํ•ฉ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ
* ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•ด ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•œ ํ›„ ๊ตฌํ•œ ๊ฒฐ๊ณผ๊ฐ’์—์„œ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ ํ•ด๊ฒฐ
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(2^(target size))
* -> target ๊ฐ’์„ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์ฐพ๋Š” ๊ณผ์ •
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(2^(target size))
* -> removeDuplicates๋Š” ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋จ. ์ค‘๋ณต์„ ์ œ์™ธํ•˜๋Š” ๊ณผ์ •์—์„œ O(2^(target size))๊ฐœ์˜ ๋ฆฌ์ŠคํŠธ ์‚ฌ์šฉ
* */
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^(target size))
* -> target ๊ฐ’์„ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์ฐพ๋Š” ๊ณผ์ •
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(target size)
* -> ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ณต๊ฐ„์ด target ๊ฐ’์— ๋น„๋ก€ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ์žฌ๊ท€ ๊นŠ์ด๋Š” O(target size)
* */
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
}

0 comments on commit dafbd2f

Please sign in to comment.