zoukankan      html  css  js  c++  java
  • [LeetCode] 322. Coin Change(换硬币)

    Description

    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.
    给你一堆不同面额的硬币和一个钱数 amount,写一个函数计算用这些硬币凑出 amount 数量的钱,所需的最少硬币数。如果这堆硬币凑不出 amount 数量的钱,返回 -1

    You may assume that you have an infinite number of each kind of coin.
    你可以假设每种硬币的数量足够多。

    Examples

    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
    

    Constraints

    • 1 <= coins.length <= 12
    • 1 <= coins[i] <= 2^31 - 1
    • 0 <= amount <= 1e4

    Solution

    这题应该也算是动态规划的例题了吧?为了求解方便,先将 coins 升序排列,定义 dp[i][j] 表示“当取前 i 种硬币来凑 j 数量的钱时,所需的最少硬币数”。问题转换为求解 dp[coins.lastIndex][amount]。初始时,dp[i][0] 设置为 0(啥都不取,可以换一个数量为 0 的钱),其余 dp[i][j] 设置为一个很大的值(比如 INT_MAX),dp[i][j] 由以下条件决定:

    • 若当前 j 大于 coins[i],则 dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i]] + 1)

    • 否则,dp[i][j] = dp[i - 1][j]

    对于第一种硬币 coins[0] 来说:

    • 若当前 j 大于 coins[0],则 dp[i][j] = min(dp[i][j], dp[i][j - coins[0]] + 1)

    当然,对于第一种硬币还有另外的方法初始化。代码如下:

    import kotlin.math.min
    
    class Solution {
        fun coinChange(coins: IntArray, amount: Int): Int {
            if (amount == 0) {
                return 0
            }
            coins.sort()
            val dp = Array(coins.size) { IntArray(amount + 1) { Int.MAX_VALUE / 2 } }
            coins.indices.forEach { dp[it][0] = 0 }
            (1..amount).forEach {
                if (it >= coins[0]) {
                    dp[0][it] = min(dp[0][it], dp[0][it - coins[0]] + 1)
                }
            }
    
            for (i in 1..coins.lastIndex) {
                for (j in 1..amount) {
                    if (j >= coins[i]) {
                        dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i]] + 1)
                    } else {
                        dp[i][j] = dp[i - 1][j]
                    }
                }
            }
    
            val result = dp.last().last()
            if (result == Int.MAX_VALUE / 2) {
                return -1
            }
            return result
        }
    }
    
  • 相关阅读:
    Windows Internals学习笔记(八)IO系统
    FPGA相关术语(一)
    Bilinear Filter
    总线与接口
    GPIO相关知识
    .NET IL学习笔记(一)
    Windows Internals学习笔记(七)Image Loader
    Windows Internals学习笔记(五)Synchronization
    struts2官方 中文教程 系列五:处理表单
    struts2官方 中文教程 系列四:Action
  • 原文地址:https://www.cnblogs.com/zhongju/p/14092972.html
Copyright © 2011-2022 走看看