518. 零钱兑换 II
一、题目
给你一个整数数组 coins
表示不同面额的硬币,另给一个整数 amount
表示总金额。
请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额,返回 0
。
假设每一种面额的硬币有无限个。
题目数据保证结果符合 32 位带符号整数。
二、思路
三、代码
class Solution { public: int change(int amount, vector<int>& coins) { vector<int> dp(amount + 1); dp[0] = 1; for (int& coin : coins) { for (int i = coin; i <= amount; i++) { dp[i] += dp[i - coin]; } } return dp[amount]; } };
四、分析
杂度分析
时间复杂度:O(amount×n),其中 amount是总金额,n 是数组 coins的长度。需要使用数组 coins 中的每个元素遍历并更新数组 dp 中的每个元素的值。
空间复杂度:O(amount),其中 amount 是总金额。需要创建长度为 amount+1 的数组 dp。