美文网首页
322 .coinChange

322 .coinChange

作者: lqsss | 来源:发表于2018-03-25 19:41 被阅读0次

题目

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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

思路

核心:动态规划
dp[amount]:表示当前amount的最小硬币组合数
状态转移方程:dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1)
比较两种情况:1. 不取当前的硬币,dp[i]
2. 取当前硬币的话,dp[i - coins[j]] + 1

代码

    public int coinChange(int[] coins, int amount) {
        if (amount == 0) return 0;
        int[] dp = new int[amount + 1];//当前amount需要的硬币数
        for (int i = 1; i < dp.length; i++) {
            dp[i] = Integer.MAX_VALUE;
        }
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.length; j++) {
                if (i >= coins[j] && dp[i - coins[j]] != Integer.MAX_VALUE) {
                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }

相关文章

  • 322 .coinChange

    题目 思路 核心:动态规划dp[amount]:表示当前amount的最小硬币组合数状态转移方程:dp[i] = ...

  • 无标题文章

    322

  • LeetCode-322-零钱兑换

    LeetCode-322-零钱兑换 322. 零钱兑换[https://leetcode-cn.com/probl...

  • 322

    十个月25天 周二。 妈妈爸爸来武汉了。 布丁在乡下,奶奶家。

  • 322

  • 322

  • 322

    祝你岁月无波澜,敬我余生不悲欢。322

  • 322

    最近读老子,慢学论语。现在每天读一遍,最初几天,每天都安排在睡前,81章读起来要近半小时,声音也很小,心里总想着快...

  • 322

    今天早上很晚才起床。作为一个年轻人,我觉得这样的行为是应该被深深鄙视的。早上七点半的时候我开了音乐,小罗又开始嚷嚷...

  • 322

    第一个休息,今天去王颖家蹭了饭,三个菜,外加我打翻的饮料,真的是太丢人了,每次都会打翻东西的我,这次还是和人家第一...

网友评论

      本文标题:322 .coinChange

      本文链接:https://www.haomeiwen.com/subject/yxrkcftx.html