Question
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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Hide Tags Dynamic Programming
My first try
Wrong Output
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if len(coins)==0:
return -1
coins = sorted(coins,reverse=True)
res = 0
for cur_coin in coins:
while amount >= cur_coin:
res += 1
amount -= cur_coin
if amount!=0:
return -1
return res
Input: [186,419,83,408], 6249
Output: -1
Expected: 20
There is a logic bug here
9=3×3×3
if coins = [3, 8], the res is -1 not 3.
Other'’s Solution
Get idea from here.
the first try
Time exceeds
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if len(coins)==0:
return -1
dp = [float('inf')] * (amount+1)
dp[0] = 0
for ind in xrange(amount+1):
for c in coins:
if ind+c<=amount:
dp[ind+c] = min(dp[ind+c], dp[ind]+1)
return dp[-1] if dp[-1]!=float('inf') else -1
Accept
For max_num, use 0x7fffffff instead of float(‘inf’) to bolster speed
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if len(coins)==0:
return -1
INF = 0x7fffffff
#INF = float('inf')
dp = [INF] * (amount+1)
dp[0] = 0
for ind in xrange(amount+1):
for c in coins:
if ind+c<=amount:
dp[ind+c] = min(dp[ind+c], dp[ind]+1)
return dp[-1] if dp[-1]!=INF else -1