518. 零钱兑换 II 力扣 动态规划,中等吧

给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。 

输入: amount = 5, coins = [1, 2, 5]
输出: 4
解释: 有四种方式可以凑成总金额:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

题源:https://leetcode-cn.com/problems/coin-change-2/

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        if (amount==0) return 1;  //我以为是0呢,如果amount=0,结果为1
      int k=coins.size();
      int f[5005];
      for(int i=0;i<=amount;i++) f[i]=0;
      f[0]=1;
      for (int i=0;i<k;i++)
        for(int j=1;j<=amount;j++)
            if (j>=coins[i]) f[j]=f[j]+f[j-coins[i]];
        
      return f[amount];
    }
};

 

posted on 2021-06-11 10:28  Yxter  阅读(58)  评论(0编辑  收藏  举报

导航