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 This is actually a completely knapsack problem, this equation we define F (amount),
 14  will be n-items into the backpack amount of capacity, the amount of such items exactly amount is a minimum number of coins required.
15  we will consider the i-th item into the required number of coins
 16  F (AMOUNT) = min (F (Coins-AMOUNT [i]) + 1)
 . 17  of the coin 1
 18 is  [0, 1, 2, 3, 4 , 5, 6, 7, 8, 9, 10, 11]
 19  coin 2
 20 is  [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6]
 21  coin 5
 22 is  [0 ,. 1,. 1, 2, 2,. 1, 2, 2,. 3,. 3, 2,. 3]
 23 is  "" " 
24  class Solution1:
 25      DEF coinChange (Self, Coins, AMOUNT):
 26 is          DP = [a float ( ' INF ' )] * (+ AMOUNT. 1) #Positive infinity float ( 'inf') minus infinity a 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'd)    # !!! dynamic programming equation, maintains an array 
31 is          return -1 IF DP [-1]> AMOUNT the else DP [-1] # if the final solution of f (amount)> amount, it indicates no solution 
32  
33 is  "" " 
34  backtracking, understand,
 35  here we first coins decreasing order, this is because we want the number of coins as low as possible,
 36  then the need for a large denomination coins as possible results in added intermediate pruning operation is easy to understand
 37 Coins IF [I] <= target <Coins [I] * (Result - COUNT):
 38 is  our target value must be greater than or equal to we will put the coin size, number of coins and this must be used than the previous less.
39  "" " 
40  class Solution2:
 41 is      DEF coinChange (Self, Coins, AMOUNT):
 42 is          coins.sort (Reverse = True)
 43 is          len_coins, Result = len (Coins), AMOUNT. 1 +
 44 is  
45          DEF countCoins (index, target, COUNT):
 46 is              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

 

Guess you like

Origin www.cnblogs.com/yawenw/p/12298704.html