Leetcode 332, 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.

 

本题不能用greedy algorithm。因为硬币的组合可能不是greedy basis。离散的问题求极值一般还是使用DP。

 

 1 class Solution(object):
 2     def coinChange(self, coins, amount):
 3         """
 4         :type coins: List[int]
 5         :type amount: int
 6         :rtype: int
 7         """
 8         int_max = 2147483647
 9         dp = [0]+[int_max]*amount
10         
11         for i in range(amount+1):
12             for coin in coins:
13                 if coin <= i:
14                     dp[i] = min(dp[i],dp[i-coin]+1)
15         
16         if dp[amount] < int_max:
17             return dp[amount]
18         else:
19             return -1

 

posted @ 2016-11-26 15:38  lettuan  阅读(201)  评论(0编辑  收藏  举报