leetcode322 Coin Change
1 """ 2 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. 3 Example 1: 4 Input: coins = [1, 2, 5], amount = 11 5 Output: 3 6 Explanation: 11 = 5 + 5 + 1 7 Example 2: 8 Input: coins = [2], amount = 3 9 Output: -1 10 """ 11 """ 12 传送门:https://blog.csdn.net/qq_17550379/article/details/82909656 13 这实际上是一个完全背包问题,我们定义这样的方程f(amount), 14 我们将n个物品放入容量为amount的背包中,使得物品金额正好为amount是,所需的硬币数目最少。 15 我们会考虑第i个物品放入后,所需硬币数目 16 f(amount)=min(f(amount-coins[i])+1) 17 硬币1 18 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 19 硬币2 20 [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6] 21 硬币5 22 [0, 1, 1, 2, 2, 1, 2, 2, 3, 3, 2, 3] 23 """ 24 class Solution1: 25 def coinChange(self, coins, amount): 26 dp = [float('inf')]*(amount+1) #正无穷 float('inf') 负无穷 float('-inf') 27 dp[0] = 0 28 for coin in coins: 29 for i in range(coin, amount+1): 30 dp[i] = min(dp[i], dp[i-coin]+1) #!!!动态规划方程,维护一个数组 31 return -1 if dp[-1] > amount else dp[-1] #如果最后解出的f(amount)>amount,那么表示无解 32 33 """ 34 回溯法,未理解 35 这里我们首先将coins从大到小进行排序,这是因为我们希望硬币数量尽可能的少, 36 那么就需要尽量将面值大的硬币加入结果中。中间的剪枝操作也很容易理解 37 if coins[i] <= target < coins[i]*(result - count): 38 我们的目标值一定是要大于等于我们将要放入的硬币面额,而且本次使用的硬币数量一定要比上次少。 39 """ 40 class Solution2: 41 def coinChange(self, coins, amount): 42 coins.sort(reverse=True) 43 len_coins, result = len(coins), amount+1 44 45 def countCoins(index, target, count): 46 nonlocal result 47 if not target: 48 result = min(result, count) 49 50 for i in range(index, len_coins): 51 if coins[i] <= target < coins[i]*(result - count): 52 countCoins(i, target - coins[i], count+1) 53 54 for i in range(len_coins): 55 countCoins(i, amount, 0) 56 return -1 if result > amount else result