322. Coin Change 找零钱 code

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.

思路:

钞票面值:coins=[1,2,5,7, 10];金额:14;dp[i]代表金额i的最优解(即最小使用张数);数组dp中存储金额1至金额14的最优解(最少使用钞票的数量)。
在计算dp[i]时,dp[0]、 dp[1]、 dp[2]、 …、 dp[i-1]都是已知的:
而金额i可由:
金额i-1与coins[0]组合;
金额i-2与coins[1]组合;
金额i-5与coins[2]组合;
金额i-7与coins[3]组合;
金额i- 10与coins[4]组合;
即,状态可由状态i1、i-2、 i-5、i-7、i-10, 5个状态所转移到,故,dp[i] = min(dp[i-1], dp[i-2], dp[i-5], dp[i-7], dp[i-10])+ 1

设i代表金额, coins[j]代表第j个面值的金额:

for j in range(len(coins)):
	dp[i] = min(dp[i],dp[i-coins[j]] + 1) # 后面的dp[i]i表示前面一步计算出来的dp[i - coins[j]] + 1中几个的最小值。
	# 或者
for j in coins:
	dp[i] = min(dp[i],dp[i-j] + 1)
from typing import List
class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        dp = [amount] * (amount+1) # 给dp赋初值amount # dp = [amount for i in range(amount+1)]
#         print(dp)
        dp[0] = 0
        for i in range(1,amount+1):
            for j in coins: # for j in range(len(coins)):
                if i >= j:
                    dp[i] = min(dp[i],dp[i-j] + 1)
        if dp[amount] == amount+1:
            return -1
        else:
            return dp[amount]
coins = [1, 2, 5]
amount = 11
solution = Solution()
solution.coinChange(coins,amount)

猜你喜欢

转载自blog.csdn.net/Frank_LJiang/article/details/106220207