-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoin Change.py
More file actions
63 lines (49 loc) · 1.55 KB
/
Coin Change.py
File metadata and controls
63 lines (49 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'''
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
'''
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dic = {0: 0}
res = self.find(coins, dic, amount)
if res == float('inf'):
return -1
return res
def find(self, coins, dic, amount):
if amount in dic:
return dic[amount]
res = float('inf')
for c in coins:
if amount >= c:
res = min(res, self.find(coins, dic, amount - c) + 1)
dic[amount] = res
return dic[amount]
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
f = [float('inf') for i in xrange(amount + 1)]
f[0] = 0
for c in coins:
for i in xrange(c, len(f)):
f[i] = min(f[i], f[i-c] + 1)
if f[-1] == float('inf'):
return -1
else:
return f[-1]