博客
关于我
322. 零钱兑换
阅读量:521 次
发布时间:2019-03-07

本文共 1118 字,大约阅读时间需要 3 分钟。

重新优化后的内容如下:

硬币改变问题常用动态规划法解决,目标是找到组成给定金额所需的最少硬币数量。以下代码示例展示了该算法的实现思路。

public int coinChange(int[] coins, int amount) {    if (amount == 0)        return 0;    if (coins == null || coins.length == 0)        return -1;        int[] dp = new int[amount + 1];    for (int i = 1; i <= amount; i++) {        int min = Integer.MAX_VALUE;        for (int face : coins) {            if (face > i)                continue;            int value = dp[i - face];            if (value < 0 || value > min)                continue;            min = value;        }        if (min == Integer.MAX_VALUE)            dp[i] = -1;        else            dp[i] = min + 1;    }    return dp[amount];}
  • 初始化状态数组:创建一个名为dp的数组,其长度为目标金额加1。dp[i]表示组成金额i所需的最少硬币数。初始化时,dp[0]通常为0,因为不需要硬币可以组成0元。

  • 定义递推关系:对于每一个金额i(从1到amount),初始化一个min值为最大可能值(Integer.MAX_VALUE)。然后遍历每一个硬币的面值face

    • 如果面值face大于当前金额i,跳过。
    • 对于每个有效的面值face,获取组成金额i-face所需的硬币数量。若dp[i-face]值为负数或大于当前min值,则忽略这种情况。
    • 更新min为找到最小的硬币数量。
    • 如果遍历结束后min仍为最大可能值,说明无法组成金额i,设为-1。如果自然得到的最少硬币数是可行的,则设为min + 1
  • 返回结果:最终,dp[amount]中存储的值即为组成给定金额所需的最少硬币数量。若无法组成,该值为-1。

  • 此算法通过一次遍历所有可能金额,并对每个金额尝试每个硬币面值,时间复杂度为O(n*m),其中n为金额,m为硬币面值数量。

    转载地址:http://moznz.baihongyu.com/

    你可能感兴趣的文章
    npm和yarn的使用对比
    查看>>
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>