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

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

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

动态规划的题目,我们首先构造一个动态数组dp[],dp[i]代表amount为i时能组成数量i所使用的最少硬币数量。如果i == coins[x]时 dp[i] = 1; 如果i > coins[x]时, 查看dp[i - coins[x]],如果dp[i-coins[x]] 已经被组成,dp[i] = Math.min(dp[i], dp[i - coins[x]] + 1)。代码如下:
public class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        for(int i = 1; i < dp.length; i++) dp[i] = Integer.MAX_VALUE;
        for(int i = 1; i < dp.length; i++) {
            for(int j = 0; j < coins.length; j++) {
                if(i - coins[j] == 0) {
                    dp[i] = 1;
                    break;
                } 
                int val = i - coins[j];
                if(val > 0 && dp[val] != Integer.MAX_VALUE) {
                    dp[i] = Math.min(dp[i], dp[val] + 1);
                }
            }
        }
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2279401
今日推荐