coin change
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.
这是一道典型的完全DP,首先需要判断是否能凑整,注意初始状态不能全为0,代码如下:
class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ if amount == 0: return 0 dp = [amount+1]*(amount+1) dp[0] = 0 # fit completely for i in xrange(len(coins)): for j in xrange(coins[i], amount+1): dp[j] = min(dp[j], dp[j-coins[i]]+1) if dp[amount] == amount+1: return -1 else: return dp[amount]
posted on 2018-03-05 23:49 Sheryl Wang 阅读(125) 评论(0) 编辑 收藏 举报