55
66class Solution :
77 def coinChange (self , coins : List [int ], amount : int ) -> int :
8- return self .solve_with_dfs (coins , amount )
8+ return self .solve_with_dp (coins , amount )
99
10- """
11- Runtime: 2039 ms (Beats 5.01%)
12- Time Complexity: ?
13-
14- Memory: 16.81 MB (Beats 11.09%)
15- Space Complexity: ?
16- """
17-
18- # TIME LIMIT
19- def solve_with_dfs (self , coins : List [int ], amount : int ) -> int :
10+ # Unbounded Knapsack Problem
11+ def solve_with_dp (self , coins : List [int ], amount : int ) -> int :
2012 if amount == 0 :
2113 return 0
2214
23- result = float ('INF' )
24- stack = []
25- for coin in coins :
26- stack .append ([[coin ], coin ])
27- while stack :
28- curr_coins , curr_amount = stack .pop ()
15+ coins .sort ()
2916
30- if amount < curr_amount :
31- continue
17+ if amount < coins [ 0 ] :
18+ return - 1
3219
33- if curr_amount == amount :
34- result = min (result , len (curr_coins ))
20+ dp = [[0 ] * (amount + 1 ) for _ in range (len (coins ) + 1 )]
21+ for curr_r in range (1 , len (coins ) + 1 ):
22+ coin_index = curr_r - 1
23+ curr_coin = coins [coin_index ]
24+ if amount < curr_coin :
25+ continue
3526
36- for coin in coins :
37- stack .append ([curr_coins + [coin ], curr_amount + coin ])
27+ dp [curr_r ][curr_coin ] += 1
28+ for curr_amount in range (curr_coin + 1 , amount + 1 ):
29+ for coin in coins :
30+ if 0 < dp [curr_r ][curr_amount - coin ]:
31+ dp [curr_r ][curr_amount ] = max (dp [curr_r - 1 ][curr_amount ], dp [curr_r ][curr_amount - coin ] + 1 )
32+ else :
33+ dp [curr_r ][curr_amount ] = dp [curr_r - 1 ][curr_amount ]
3834
39- return - 1 if result == float ( 'INF' ) else result
35+ return dp [ - 1 ][ - 1 ] if 0 < dp [ - 1 ][ - 1 ] else - 1
4036
4137
4238class _LeetCodeTestCases (TestCase ):
@@ -58,6 +54,12 @@ def test_3(self):
5854 output = 0
5955 self .assertEqual (Solution .coinChange (Solution (), coins , amount ), output )
6056
57+ def test_4 (self ):
58+ coins = [1 , 2147483647 ]
59+ amount = 2
60+ output = - 1
61+ self .assertEqual (Solution .coinChange (Solution (), coins , amount ), output )
62+
6163
6264if __name__ == '__main__' :
6365 main ()
0 commit comments