[leetcode]Coin Change
来源:互联网 发布:手机fm发射器软件 编辑:程序博客网 时间:2024/04/27 20:08
题目描述如下:
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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
将一个大面额的钱分成若干指定面额的零钱,问最少需要多少枚。
分析:dp问题。可以将其分解为重叠的子问题进行解决。
在本题的思路中,设置一个一维数组来保存构成面值N所需要的最小零钱数量,然后两重循环循环填充数组,最后输出答案。
感觉分析很难讲清楚,代码还是比较好理解的:
public class Solution { public int coinChange(int[] coins, int amount) { final int MaxNum = 100000; int res = MaxNum; int []countArray = new int[amount + 1]; countArray[0] = 0; // 必要的初始化 int tmp; for(int i = 1; i <= amount; i++) { tmp = MaxNum; for (int coinValue : coins) { // 每次循环最终确定最小数量 if (i >= coinValue) { if (tmp > countArray[i - coinValue] + 1) tmp = countArray[i - coinValue] + 1; } } countArray[i] = tmp; } res = countArray[amount]; if(res == MaxNum) return -1; else return res; }}
题目链接:https://leetcode.com/problems/coin-change/
0 0
- leetcode Coin Change
- Leetcode: Coin Change
- LeetCode Coin Change
- [leetcode] 322. Coin Change
- Leetcode: Coin Change
- [LeetCode 322] Coin Change
- leetcode--Coin Change
- [leetcode]Coin Change
- leetcode 322. Coin Change
- leetcode:Coin Change
- leetcode之Coin Change
- Leetcode 322. Coin Change
- Leetcode 322. Coin Change
- leetcode笔记:Coin Change
- leetcode 322 Coin Change
- 322. Coin Change LeetCode
- 【LeetCode-322】Coin Change
- leetcode之 coin change
- Android UI 基础之 Menu使用大全
- android shape的使用
- js实现页面跳转重定向的几种方式
- Windows下Git的安装和基本使用方法
- ADS2015安装
- [leetcode]Coin Change
- 4、React对组件的DOM事件监听
- Android Studio 快捷键
- xcode 左边导航栏中,类文件后面的标记字母的意义
- gitbub for windows 环境搭建与代码同步
- iReport与JasperReport PDF中文解决
- rqnoj 1 去重+排序
- 虚函数表
- 给自己的一些提醒