[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