美文网首页
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

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