https://leetcode.com/problems/coin-change/css
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
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