LeetCode刷题之322 Coin Change

本文介绍了如何使用动态规划算法解决寻找最少硬币组合的问题。通过递归和迭代两种方式实现,分别展示了带备忘录的递归解法和迭代解法。在给定的不同面额硬币及总金额条件下,找出组成该金额所需的最少硬币数。对于无法组成目标金额的情况,返回-1。动态规划的核心在于优化穷举过程,以减少计算次数并提高效率。

1. Description

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

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

2. Test Cases

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

Example 3:

Input: coins = [1], amount = 0
Output: 0

Example 4:

Input: coins = [1], amount = 1
Output: 1

Example 5:

Input: coins = [1], amount = 2
Output: 2

3. Solution

3.1 带备忘录递归

class Solution {
    public int coinChange(int[] coins, int amount) {
        Integer[] dp = new Integer[amount +1];
        dp[0] = 0;
        
        find(coins, amount, dp);
        
        return dp[amount];
    }
    
    private int find(int[] coins, int amount, Integer[] dp) {
        if (amount == 0) return 0;
        
        if(dp[amount] != null )
            return dp[amount];
        
        int min =Integer.MAX_VALUE;
        
        for (int c : coins) {
            if (amount -c >= 0) {
                int r = find(coins, amount-c, dp);
                if (r != -1)
                    min = Math.min(min, r + 1);
            }
        }
        
        return dp[amount] = (min == Integer.MAX_VALUE ? -1 : min);
    }
    
}

3.2 iterative

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

4. 思考

似乎动态规划的本质就是穷举,只是如何穷举更少的次数,更快的得到结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值