Skip to content

Commit 3c35048

Browse files
committed
coin-change solution (py)
1 parent 91e86a9 commit 3c35048

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

β€Žcoin-change/hi-rachel.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
# BFS -> λ¨Όμ € μ°ΎλŠ” 해닡이 κ°€μž₯ 적은 μ—°μ‚°/κ°€μž₯ 짧은 거리 -> κ°€μž₯ 적은 countλΆ€ν„° 계산해 μ΅œμ†Œν•œμ˜ 동전 수 보μž₯
3+
# O(amount * n) time, O(amount) space
4+
5+
from collections import deque
6+
7+
class Solution:
8+
def coinChange(self, coins: List[int], amount: int) -> int:
9+
queue = deque([(0, 0)]) # (동전 개수, ν˜„μž¬ κΈˆμ•‘)
10+
visited = set()
11+
while queue:
12+
count, total = queue.popleft()
13+
if total == amount:
14+
return count
15+
if total in visited:
16+
continue
17+
visited.add(total)
18+
for coin in coins:
19+
if total + coin <= amount:
20+
queue.append((count + 1, total + coin))
21+
return - 1
22+
23+
24+
# DP 풀이
25+
# μ–΄λ–€ κΈˆμ•‘μ„ λ§Œλ“œλŠ”λ° ν•„μš”ν•œ 동전 개수λ₯Ό μ•Œλ©΄, κ·Έ κΈˆμ•‘λ³΄λ‹€ 큰 κΈˆμ•‘μ„ λ§Œλ“œλŠ”λ° ν•„μš”ν•œ 동전 κ°œμˆ˜λ„ μ•Œ 수 μžˆλ‹€.
26+
# dp[i] = min(dp[i], dp[i - coin] + 1)
27+
# O(amount * n) time, O(amount) space
28+
29+
class Solution:
30+
def coinChange(self, coins: List[int], amount: int) -> int:
31+
dp = [0] + [amount + 1] * amount
32+
33+
for coin in coins:
34+
for i in range(coin, amount + 1):
35+
dp[i] = min(dp[i], dp[i - coin] + 1)
36+
37+
return dp[amount] if dp[amount] < amount + 1 else -1

0 commit comments

Comments
Β (0)