forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
แแ
ตแแ
งแซแแ
ฎ
committed
Jan 2, 2025
1 parent
7740c13
commit dafbd2f
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |