Skip to content

Commit c9eb708

Browse files
author
sangbeenmoon
committed
solved coin-change.
1 parent 3b8b30e commit c9eb708

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

coin-change/sangbeenmoon.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# dp[i] = min(dp[i - c0], dp[i - c1], ... , dp[i - cn]) + 1
2+
3+
# TC : O(amount * len(coins))
4+
# SC : O(amount)
5+
6+
class Solution:
7+
dp = []
8+
def coinChange(self, coins: List[int], amount: int) -> int:
9+
self.dp = [-2] * (amount + 10) # 아직 방문하지 않음 -> -2
10+
11+
return self.go(amount, coins)
12+
13+
14+
def go(self, x: int, coins: List[int]) -> int:
15+
if x == 0:
16+
return 0
17+
18+
if self.dp[x] != -2:
19+
return self.dp[x]
20+
21+
mm = 100000
22+
23+
for coin in coins:
24+
if x - coin >= 0:
25+
sub = self.go(x - coin, coins)
26+
if (sub == -1): # 불가능 -> -1
27+
continue
28+
mm = min(mm, sub + 1)
29+
30+
self.dp[x] = mm if mm != 100000 else -1 # memoization
31+
32+
return self.dp[x]

0 commit comments

Comments
 (0)