Leetcode 322. Coin Change

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

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:ide

Input: coins = , amount = 
Output:  
Explanation: 11 = 5 + 5 + 1[1, 2, 5]113

Example 2:spa

Input: coins = , amount = 
Output: -1
[2]3

Note:
You may assume that you have an infinite number of each kind of coin.code


  • 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
相關文章
相關標籤/搜索