首页 > 其他 > 详细

0322. Coin Change (M)

时间:2020-06-27 10:22:47      阅读:51      评论:0      收藏:0      [点我收藏+]

Coin Change (M)

题目

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.


题意

选数量最少的硬币,使其和为amount。

思路

动态规划,由局部最优解求得全局最优解:设F(N)为和为N的硬币的最小个数,C为某一硬币的面值,那么很容易得到 F(N) = F(N - C) + 1,那么只要求得F(N - C)的最小值,就能得到F(N)的最小值。


代码实现

Java

记忆化

class Solution {
    public int coinChange(int[] coins, int amount) {
        return dfs(coins, amount, new int[amount + 1]);
    }

    private int dfs(int[] coins, int remain, int[] record) {
        if (remain < 0) {
            return -1;
        }
        if (remain == 0) {
            return 0;
        }
        if (record[remain] != 0) {
            return record[remain];
        }

        int min = Integer.MAX_VALUE;
        for (int coin : coins) {
            int count = dfs(coins, remain - coin, record);
            if (count >= 0 && count + 1 < min) {
                min = count + 1;
            }
        }

        record[remain] = min == Integer.MAX_VALUE ? -1 : min;
        return record[remain];
    }
}

动态规划

class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int coin : coins) {
                if (i >= coin) {
                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                }
            }
        }
        return dp[amount] == amount + 1 ? -1 : dp[amount];
    }
}

0322. Coin Change (M)

原文:https://www.cnblogs.com/mapoos/p/13197372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!