leetcode [322]Coin Change

Posted xiaobaituyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode [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 1:

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

Example 2:

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

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

题目大意:

给一大把硬币,看组成钱数的最少硬币个数是多少,每种钱数的硬币不限制数量。如果不能组成该钱数,则返回-1。

解法:

我采用动态规划的方法来做,使用dp[i]来记录组成该钱数的最少硬币数量,但是这种做法超时了,我也觉得如果这样做,时间复杂度是O(amount*amount)。

在更新dp数组的时候采用的是前面的dp来更新后面的dp,结果TLE了。

java:

class Solution {
    public int coinChange(int[] coins, int amount) {
        if (coins.length==0||amount<0) return -1;
        if (amount==0) return 0;
        int res=-1;
        int[] dp=new int[amount+1];
        Arrays.fill(dp,Integer.MAX_VALUE);
        int n=coins.length;
        for (int i=0;i<n;i++) {
            if (coins[i]>amount) continue;
            dp[coins[i]]=1;
        }
        dp[0]=0;
        for (int i=1;i<=amount;i++){
            if (dp[i]==1) continue;
            for (int j=i-1;j>=i/2;j--){
                if (dp[j]!=Integer.MAX_VALUE && dp[i-j]!=Integer.MAX_VALUE)
                    dp[i]=Math.min(dp[i],dp[j]+dp[i-j]);
            }
        }

        return dp[amount]==Integer.MAX_VALUE?-1:dp[amount];
    }
}

在更新dp数组的时候,应该使用已有的硬币来更新dp数组。

优化过后的java:

class Solution {
    public int coinChange(int[] coins, int amount) {
        if (coins.length==0||amount<0) return -1;
        if (amount==0) return 0;
        int res=-1;
        int[] dp=new int[amount+1];
        Arrays.fill(dp,Integer.MAX_VALUE);
        int n=coins.length;
        dp[0]=0;
        for (int i=1;i<=amount;i++){
            for (int j=0;j<coins.length;j++){
                if (coins[j]<=i && 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];
    }
}

以上是关于leetcode [322]Coin Change的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-322-Coin Change]

322. Coin Change(leetcode )

Leetcode322. Coin Change

[Leetcode] 322. Coin Change

LeetCode-322.Coin Change

leetcode [322]Coin Change