Leetcode 322. Coin Change

https://leetcode.com/problems/coin-change/

Medium

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.


  • DP。注意 coins = [1], amount = 0时,结果为0。
  • 第一种在深搜的基础上,自顶向下带记忆数组储存结果。
  • 第二种自底向上。f[ i ] 代表amount为i时最少硬币数目。f[ i ] = min { f[ i - coin[ k ] ] }, f[ 0 ] = 0。
  • https://leetcode.com/problems/coin-change/solution/
 1 class Solution:
 2     # DP Top down with memoization table
 3     def coinChange1(self, coins: List[int], amount: int) -> int:
 4         if amount < 1:
 5             # should be 0 rather than -1
 6             return 0
 7         
 8         counts = [0] * (amount + 1)
 9         
10         def helper(amount):
11             if amount == 0:
12                 return 0
13             
14             if counts[amount] != 0:
15                 return counts[amount]
16             
17             min_result = float('inf')
18             
19             for coin in coins:
20                 if amount < coin:
21                     continue
22                     
23                 result = helper(amount - coin) + 1
24                 
25                 if 0 < result < min_result:
26                     min_result = result
27             
28             counts[amount] = -1 if min_result == float('inf') else min_result
29             
30             return counts[amount]
31         
32         return helper(amount)
33 
34     # DP Bottom up
35     def coinChange(self, coins: List[int], amount: int) -> int:
36         if amount < 1:
37             # should be 0 rather than -1
38             return 0
39         
40         dp = [float('inf')] * (amount + 1)
41         dp[0] = 0
42         
43         for i in range(0, amount + 1):
44             for coin in coins:
45                 if i >= coin:
46                     dp[i] = min(dp[i], dp[i - coin] + 1)
47         
48         return dp[amount] if dp[amount] != float('inf') else -1
View Python Code

 

posted on 2019-09-17 14:02  浩然119  阅读(170)  评论(0编辑  收藏  举报