Skip to content

Commit 2601edb

Browse files
committed
coin change solution
1 parent e6160eb commit 2601edb

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

โ€Žcoin-change/radiantchoi.pyโ€Ž

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from collections import deque
2+
3+
class Solution:
4+
def coinChange(self, coins: List[int], amount: int) -> int:
5+
# dp[i]: amount๊ฐ€ i์ผ ๋•Œ ์ตœ์†Œ ๋™์ „ ์‚ฌ์šฉ ํšŸ์ˆ˜
6+
# ๋ชจ๋“  ๊ฒฝ์šฐ ๋ฐฉ๋ฒ•์ด ์—†๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ  -1๋กœ ์ดˆ๊ธฐํ™”
7+
dp = [-1 for _ in range(amount + 1)]
8+
9+
# bfs ์…‹์—… - ํ•ฉ์ด 0์ธ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ณ , ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
10+
dp[0] = 0
11+
q = deque([[0, 0]])
12+
13+
while q:
14+
# ํ˜„์žฌ ๋…ธ๋“œ์˜ ์‚ฌ์šฉ ํšŸ์ˆ˜์™€ ํ•ฉ
15+
current = q.popleft()
16+
17+
# ๊ฐ๊ฐ์˜ ๋™์ „์€ ๋ฌดํ•œํžˆ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ ๋ชจ๋‘ ํƒ์ƒ‰
18+
for coin in coins:
19+
estimated = current[1] + coin
20+
21+
# ํ˜„์žฌ ๋…ธ๋“œ์˜ ํ•ฉ + ๋™์ „์˜ ๊ฐ€์น˜๊ฐ€ amount๋ฅผ ์ดˆ๊ณผํ•  ๊ฒฝ์šฐ ์Šคํ‚ต (์˜๋ฏธ์—†๋Š” ์—ฐ์‚ฐ)
22+
# bfs์˜ ํƒ์ƒ‰ ๋ฐฉ์‹์— ๋”ฐ๋ผ, ์ ์€ ํšŸ์ˆ˜๋กœ ๋ชฉํ‘œ ๊ฐ€๊ฒฉ์— ๋„๋‹ฌํ–ˆ๋‹ค๋ฉด ์ด๊ฒƒ์ด ๋” ์ตœ์ ์˜ ๊ฒฐ๊ณผ์ด๋ฏ€๋กœ ์Šคํ‚ต
23+
# ๋‘ ์กฐ๊ฑด ๋ชจ๋‘ ํ†ต๊ณผํ–ˆ๋‹ค๋ฉด ํ์— ๋„ฃ์–ด์„œ ๋‹ค์‹œ ํƒ์ƒ‰
24+
if estimated <= amount and dp[estimated] == -1:
25+
used = current[0] + 1
26+
dp[estimated] = used
27+
28+
new = [used, estimated]
29+
q.append(new)
30+
31+
# dp[amount]๊ฐ€ -1์ด๋ฉด ๋ชจ๋“  ๊ฒฝ์šฐ ๋ฐฉ๋ฒ•์ด ์—†๋‹ค๋Š” ์˜๋ฏธ์ด๋ฏ€๋กœ -1 ๋ฐ˜ํ™˜
32+
# ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด dp[amount] ๋ฐ˜ํ™˜
33+
return dp[amount]

0 commit comments

Comments
ย (0)