LeetCode : 322. Coin Change 凑齐硬币

£神魔★判官ぃ 2021-06-24 16:11 453阅读 0赞

试题
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.

代码
动态规划

  1. class Solution {
  2. public int coinChange(int[] coins, int amount) {
  3. int[] am = new int[amount+1];
  4. Arrays.fill(am, -1);
  5. am[0] = 0;
  6. for(int i = 1; i<=amount; i++){
  7. for(int c : coins){
  8. if(i-c>=0 && am[i-c]!=-1){
  9. if(am[i]==-1)
  10. am[i] = am[i-c] + 1;
  11. else
  12. am[i] = Math.min(am[i], am[i-c] + 1);
  13. }
  14. }
  15. }
  16. return am[amount];
  17. }
  18. }

发表评论

表情:
评论列表 (有 0 条评论,453人围观)

还没有评论,来说两句吧...

相关阅读

    相关 322. Coin Change(硬币兑换dp)

    您会得到不同面额的硬币和总金额。编写一个函数来计算组成该数量所需的最少数量的硬币。如果这笔钱不能用硬币的任何组合来弥补,请返回-1。 范例1: 输入:硬币= \[1, 2,