File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /*
4
+ * ์ฃผ์ด์ง ๋์ ์ ์ข
๋ฅ์ ๊ฐ์๋ฅผ ์ฌ์ฉํ์ฌ ์ฃผ์ด์ง ๊ธ์ก์ ๋ง๋ค ๋, ์ค๋ณต์ ํ์ฉํ ์ต์ ๋์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
5
+ * ๋๋น ์ฐ์ ํ์์ ์ฌ์ฉํด ๋ฌธ์ ํด๊ฒฐ
6
+ * ์๊ฐ ๋ณต์ก๋: O(n)
7
+ * -> queue ์๋ฃ๊ตฌ์กฐ์์ ๊ฐ ๋์ (n)์ ๊บผ๋ด๊ณ ๋ชฉํ ๊ธ์ก(amount == k)๊น์ง ๋๋ฌํ๋ ๊ฒฝ์ฐ: O(n * k)
8
+ * ๊ณต๊ฐ ๋ณต์ก๋: O(k)
9
+ * -> ๋์ ์ฌ์ฉ ํ์๋ฅผ ์ ์ฅํ๋ board์ ํฌ๊ธฐ
10
+ * */
11
+ fun coinChange (coins : IntArray , amount : Int ): Int {
12
+ if (amount == 0 ) return 0
13
+ if (coins.isEmpty() || coins.any { it <= 0 }) return - 1
14
+
15
+ val board = IntArray (amount + 1 ) { - 1 }
16
+ val queue = ArrayDeque <Int >()
17
+
18
+ for (coin in coins) {
19
+ if (coin <= amount) {
20
+ queue.add(coin)
21
+ board[coin] = 1 // ๋์ ํ๋๋ก ๊ตฌ์ฑ ๊ฐ๋ฅ
22
+ }
23
+ }
24
+
25
+ while (queue.isNotEmpty()) {
26
+ val currentPosition = queue.pollFirst()
27
+ for (coin in coins) {
28
+ val nextPosition = currentPosition + coin
29
+ if (nextPosition in 1 .. amount) {
30
+ // ์์ง ๋ฐฉ๋ฌธํ์ง ์์๊ฑฐ๋ ๋ ์ ์ ๋์ ์ผ๋ก ๊ตฌ์ฑ ๊ฐ๋ฅํ๋ฉด ์
๋ฐ์ดํธ
31
+ if (board[nextPosition] == - 1 || board[nextPosition] > board[currentPosition] + 1 ) {
32
+ queue.add(nextPosition)
33
+ board[nextPosition] = board[currentPosition] + 1
34
+ }
35
+ }
36
+ }
37
+ }
38
+
39
+ return board[amount]
40
+ }
You canโt perform that action at this time.
0 commit comments