零钱兑换

给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。

计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1

你可以认为每种硬币的数量是无限的。

示例 1:

1
2
3
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1

示例 2:

1
2
输入:coins = [2], amount = 3
输出:-1

示例 3:

1
2
输入:coins = [1], amount = 0
输出:0

提示:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

完全背包问题,f[i][j]表示从前i个零钱中选择组合成j的最小硬币数量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int coinChange(int[] coins, int amount) {
int n = coins.length;

// f[i][j]表示使用i种硬币,组成j元的最小硬币数量
int[][] f = new int[n + 1][amount + 1];
//因为初始化为Integer.MAX_VALUE下边加一会溢出
Arrays.fill(f[0], Integer.MAX_VALUE/2);
f[0][0] = 0;
for (int i = 1; i <= n; i++) {
int coin = coins[i - 1];
for (int j = 0; j <= amount; j++) {
if (coin > j) {
f[i][j] = f[i - 1][j];
} else {
f[i][j] = Math.min(f[i - 1][j], f[i][j - coin] + 1);
}
}
}
int ans = f[n][amount];
return ans<Integer.MAX_VALUE/2?ans:-1;
}
}

因为状态方程的转移只使用了当前行和上一行的数据,所以可以优化空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int coinChange(int[] coins, int amount) {
int n = coins.length;

// f[j]表示组成j元的最小硬币数量
int[] f = new int[amount + 1];
Arrays.fill(f, Integer.MAX_VALUE / 2);
f[0] = 0;
for (int i = 1; i <= n; i++) {
int coin = coins[i - 1];
for (int j = 0; j <= amount; j++) {
if (j >= coin) {
f[j] = Math.min(f[j], f[j - coin] + 1);
}
}
}
int ans = f[amount];
return ans < Integer.MAX_VALUE / 2 ? ans : -1;
}
}