0322. 零钱兑换【中等】
1. 📝 题目描述
给你一个整数数组 coins,表示不同面额的硬币;以及一个整数 amount,表示总金额。
计算并返回可以凑成总金额所需的 最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
你可以认为每种硬币的数量是无限的。
示例 1:
txt
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 11
2
3
2
3
示例 2:
txt
输入:coins = [2], amount = 3
输出:-11
2
2
示例 3:
txt
输入:coins = [1], amount = 0
输出:01
2
2
提示:
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4
2. 🎯 s.1 - 动态规划
c
int coinChange(int* coins, int coinsSize, int amount) {
int* dp = (int*)malloc(sizeof(int) * (amount + 1));
for (int i = 0; i <= amount; i++) dp[i] = amount + 1;
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coinsSize; j++) {
if (coins[j] <= i && dp[i - coins[j]] + 1 < dp[i])
dp[i] = dp[i - coins[j]] + 1;
}
}
int res = dp[amount] > amount ? -1 : dp[amount];
free(dp);
return res;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
js
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
const dp = new Array(amount + 1).fill(Infinity)
dp[0] = 0
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (coin <= i && dp[i - coin] + 1 < dp[i]) {
dp[i] = dp[i - coin] + 1
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount]
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
py
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [0] + [float('inf')] * amount
for i in range(1, amount + 1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -11
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 时间复杂度:
,其中 是金额, 是硬币种类数 - 空间复杂度:
,dp数组
算法思路:
表示凑成金额 所需的最少硬币数- 转移方程:
,枚举所有硬币面值