322 Coin Change

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:

Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Input: coins = [2], amount = 3
Output: -1

Note:

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

解释下题目:

1. 动态规划

实际耗时:xxms

public int coinChange(int[] coins, int amount) {
    if (amount < 1) {
        return 0;
    }
    int[] dp = new int[amount];
    return helper(coins, amount, dp);
    //System.out.println(Arrays.toString(dp));
}

private int helper(int[] coins, int left, int[] dp) {
    if (left < 0) {
        return -1;
    }
    if (left == 0) {
        //found the answer
        return 0;
    }
    if (dp[left - 1] != 0) {
        return dp[left - 1];
    }
    int min = Integer.MAX_VALUE;
    for (int coin : coins) {
        int tmp = helper(coins, left - coin, dp);
        if (tmp >= 0) {
            if (tmp < min) {
                min = tmp + 1;
            }
        }
    }
    dp[left - 1] = (min == Integer.MAX_VALUE ? -1 : min);
    return dp[left - 1];
}
踩过的坑:[186,419,83,408],6249 这组。

  首先确定这题绝对不是贪心。然后其实如果你知道amount = 500怎么求的话,其实500以下的所有数字你也知道怎么求了。然后算法有个出口,我之前搓一直错在这里,就是如果dp[left - 1] != 0,这里我之前写的是大于,其实如果是-1也算找到了答案,所以要改成不等于0,其他的应该就没难度了。

时间复杂度O(n*amount) n为coins这个数组的长度
空间复杂度O(amount)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • 参考 [LeetCode] Coin Change 硬币找零 题目描述:You are given coins o...
    小碧小琳阅读 1,194评论 0 1
  • 问题描述 You are given coins of different denominations and a...
    JERORO_阅读 168评论 0 0
  • 题目链接 tag: Medium; Dynamic Programming; question:  You are...
    xingzai阅读 97评论 0 0
  • 问题描述 You are given coins of different denominations and a...
    codingXue阅读 346评论 0 0