File tree Expand file tree Collapse file tree 1 file changed +46
-11
lines changed Expand file tree Collapse file tree 1 file changed +46
-11
lines changed Original file line number Diff line number Diff line change 1
1
class Solution :
2
2
def coinChange (self , coins : List [int ], amount : int ) -> int :
3
- n = len (coins )
3
+ # Top Down DP (Memoization)
4
+ # Time: O(Coins * Amount)
5
+ # Space: O(Amount)
6
+ coins .sort ()
7
+ memo = {0 :0 }
8
+
9
+ def min_coins (amt ):
10
+ if amt in memo :
11
+ return memo [amt ]
12
+
13
+ minn = float ('inf' )
14
+ for coin in coins :
15
+ diff = amt - coin
16
+ if diff < 0 :
17
+ break
18
+ minn = min (minn , 1 + min_coins (diff ))
19
+
20
+ memo [amt ] = minn
21
+ return minn
22
+
23
+ result = min_coins (amount )
24
+ if result < float ('inf' ):
25
+ return result
26
+ else :
27
+ return - 1
28
+
29
+
30
+
31
+ class Solution :
32
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
33
+ # Bottom Up DP (Tabulation)
34
+ # Time: O(Coins * Amount)
35
+ # Space: O(Amount)
36
+ dp = [0 ] * (amount + 1 )
4
37
coins .sort ()
5
- dp = [float ('inf' )] * (amount + 1 )
6
- dp [0 ] = 0
7
38
8
39
for i in range (1 , amount + 1 ):
40
+ minn = float ('inf' )
41
+
9
42
for coin in coins :
10
- difference = i - coin
11
- if difference < 0 :
43
+ diff = i - coin
44
+ if diff < 0 :
12
45
break
13
- dp [i ] = min (dp [i ], 1 + dp [difference ])
14
-
46
+ minn = min (minn , dp [diff ] + 1 )
47
+
48
+ dp [i ] = minn
15
49
16
- return dp [amount ] if dp [amount ] < float ('inf' ) else - 1
17
- # Let C be the number of coins and A be the amount.
18
- # Time Complexity: O(C * Amount)
19
- # Space Complexity: O(Amount)
50
+ if dp [amount ] < float ('inf' ):
51
+ return dp [amount ]
52
+ else :
53
+ return - 1
54
+
You can’t perform that action at this time.
0 commit comments