Day 17 LeetCode 322. Coin Change

换个口味来写 LeetCode,并且挑战一下不太擅长的动态规划。

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

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

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

Example 3:

Input: coins = [1], amount = 0
Output: 0

Example 4:

Input: coins = [1], amount = 1
Output: 1

Example 5:

Input: coins = [1], amount = 2
Output: 2
class Solution:

    def solve(self, coins: List[int], amount: int):

        box = [amount+1 for i in range((amount + 1))]
        box[0] = 0
        for i in range(1, amount + 1):
            for coin in coins:

                if coin <= i:
                    box[i] = min(box[i], box[i - coin] + 1)


        return -1 if box[amount] > amount else box[amount]
        pass

    def coinChange(self, coins: List[int], amount: int) -> int:

        if amount == 0:
            return 0

        return self.solve(coins, amount)

在这一题中最重要的就是 11 行的 box[i - coin] + 1,他代表继承之前的硬币数。

比如说现在要找总合 i == 10 的,当 coin == 3 时,
会找 box[7] 的硬币数并+1,
因为任何一组能构成总和 7 的硬币,只要加这一枚硬币 3 总和就是 10。


<<:  #17 数据上的各种距离(2)

>>:  Day21 - Spinner(一)

沟通这回事:ORID 与引导

前言 昨天分享了冰山理论,今天接着谈「焦点讨论法 | ORID」,并在後半延伸至引导学(Facili...

[Day_17]回圈与生成式 - (3)

巢状回圈 巢状回圈并非新的程序结构,只是回圈范围内又有回圈,巢状回圈可以有好几层,巢状回圈与单层回圈...

[30天 Vue学好学满 DAY20] Vuex-3

Mutation 提交mutation,是更动state的唯一方法,并以state为第一个参数。 包...

Day14 实作文章预览功能

接下来我们会开始实作各个页面的逻辑,每个页面需要的资料不一样,适用的渲染模式也不一样,於是今天我们会...

[Day 12] -『 GO语言学习笔记』- for range 回圈

以下笔记摘录自『 The Go Workshop 』。 Go语言只支援一种回圈回圈叙述,就是for回...