File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ class Solution :
4
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
5
+ if amount == 0 :
6
+ return 0
7
+
8
+ ## 去掉大于amount的 coins
9
+ coins = list (filter (lambda x : x <= amount , coins ))
10
+ if not coins :
11
+ return - 1
12
+ if amount < min (coins ):
13
+ return - 1
14
+
15
+ ## 初始化dp
16
+ dp = [ 0 ] * ( amount + 1 )
17
+
18
+ for i in coins :
19
+ dp [i ] = 1
20
+
21
+ dp [1 :min (coins )] = [ float ('inf' ) ] * (min (coins ) - 1 )
22
+
23
+ for i in range (min (coins ) , amount + 1 ):
24
+ min_count = float ('inf' )
25
+ j = i
26
+ while j <= i and j >= min (coins ):
27
+ if j in coins :
28
+ min_count = min (min_count , 1 + dp [i - j ])
29
+ j -= 1
30
+ dp [i ] = min_count
31
+
32
+ return dp [amount ] if dp [amount ] != float ('inf' ) else - 1
33
+
34
+ coins = [1 ,2 ,5 ]
35
+ amount = 11
36
+ print (Solution ().coinChange (coins , amount ))
37
+
You can’t perform that action at this time.
0 commit comments