0322. Coin Change (M)

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];
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/13197372.html