java零钱换整程序_(Java) LeetCode 322. 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.

动态规划典型问题,想一想递推关系是什么。假设dp[i]代表i这么多钱所需要的硬币数量,那么对于每一个不同面值的硬币coins[j]来说,dp[i] = dp[i - coins[j]] + 1。只要在遍历coins面值的时候选择需要数量最小的就好,即min(dp[i], dp[i - coins[j]] + 1)。通用情况想完了就要想初始情况。dp[0]显然是0,不需要硬币组成0元。而既然在递推中要用到min,那么把所有值初始为amount + 1的话即可,因为硬币都是正数,不可能会存在需要比amount还多硬币的情况。如果最后得到的结果比amount大(其实题里并没有说amount不会是最大正数,否则这样取值就会overflow产生错误,test case里面并没有这种情况),证明没有办法组成面值,需要返回-1。需要注意的是因为i-coins[j]作为数组下标出现,显然conis[j]不能比i大。

Java

classSolution {public int coinChange(int[] coins, intamount) {if (coins == null || coins.length == 0 || amount <= 0) return 0;int[] dp = new int[amount + 1];

Arrays.fill(dp, amount+ 1);

dp[0] = 0;for (int j = 0; j < coins.length; j++)for (int i = coins[j]; i <= amount; i++)

dp[i]= Math.min(dp[i], dp[i - coins[j]] + 1);return dp[amount] > amount ? -1: dp[amount];

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值