ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

【LeetCode】322. Coin Change 零钱兑换(Medium)(JAVA)

2020-12-16 09:04:48  阅读:237  来源: 互联网

标签:Medium JAVA int coins 322 amount Input Example dp


【LeetCode】322. Coin Change 零钱兑换(Medium)(JAVA)

题目地址: 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.

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

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

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

题目大意

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

你可以认为每种硬币的数量是无限的。

解题方法

  1. 开始采用暴力搜索 BFS(宽度优先搜索),直接超时
  2. 用动态规划,最重要的是找出状态转移函数 dp 函数:dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
  3. note: 因为可能不存在,所以要额外定义一个不存在的状态,比如 dp[i] = -1
class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.sort(coins);
        for (int i = 1; i <= amount; i++) {
            dp[i] = -1;
            for (int j = 0; j < coins.length; j++) {
                if (i - coins[j] < 0 || dp[i - coins[j]] < 0) continue;
                if (dp[i] == -1 || dp[i] > (dp[i - coins[j]] + 1)) {
                    dp[i] = dp[i - coins[j]] + 1;
                }
            }
        }
        return dp[amount];
    }
}

执行耗时:18 ms,击败了37.63% 的Java用户
内存消耗:38.1 MB,击败了54.99% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

标签:Medium,JAVA,int,coins,322,amount,Input,Example,dp
来源: https://blog.csdn.net/qq_16927853/article/details/111245119

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有