LeetCode--322--medium--CoinChange

package com.app.main.LeetCode.dynamic;

import java.util.HashMap;
import java.util.Map;

/**
 * 322
 *
 * medium
 *
 * https://leetcode.com/problems/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.
 *
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2019/12/26
 * Time:下午4:17
 */
public class CoinChange {

    private Map<Integer, Integer> cache = new HashMap<>();

    public int coinChange(int[] coins, int amount) {
        if (amount == 0) {
            return 0;
        }
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < coins.length; i++) {
            if (amount - coins[i] < 0) {
                continue;
            }
            int next = coinChange(coins, amount - coins[i]);
            if (next != -1) {
                result =  Math.min(result, 1 + next);
            }
        }
        return result == Integer.MAX_VALUE ? -1 : result;
    }

    public int coinChange2(int[] coins, int amount) {
        if (amount == 0) {
            return 0;
        }
        if (cache.containsKey(amount)) {
            return cache.get(amount);
        }
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < coins.length; i++) {
            if (amount - coins[i] < 0) {
                continue;
            }
            int next = coinChange(coins, amount - coins[i]);
            if (next != -1) {
                result =  Math.min(result, 1 + next);
            }
        }
        int res = result == Integer.MAX_VALUE ? -1 : result;
        cache.put(amount, res);
        return res;
    }

    public int coinChange3(int[] coins, int amount) {
        int dp[] = new int[amount + 1];
        // init
        for (int i = 0; i < dp.length; i++) {
            dp[i] = amount + 1;
        }

        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j : coins) {
                if (i - j >= 0) {
                    dp[i] = Math.min(dp[i], 1 + dp[i - j]);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];

    }
}
发布了187 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/103809665