#322. 零钱兑换

给定不同面额的硬币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

说明:
你可以认为每种硬币的数量是无限的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package xyz.onns.leetcode;

import java.util.Arrays;

/**
* @Author Onns
* @Date 2020/9/15 12:06 PM
* @Version 1.0
* @Website https://onns.xyz/blog/
*/
public class CoinChange {
public static void main(String[] args) {
new CoinChange().new Solution().test();
}

class Solution {
public int coinChange(int[] coins, int amount) {

int n = coins.length;
if (n == 0) return -1;
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);

// base case:
// dp[0] = 0
dp[0] = 0;

// all conditions:
// amount from 1 to amount
// coin from 0 to coins.length - 1
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < n; j++) {
// state transition:
// f(i) = f(i-coins[i]) + 1, if f(i-coins[i]) + 1 < f(i)
// f(i) = f(i), otherwise
int t = i - coins[j];
if (t >= 0) {
dp[i] = Math.min(dp[t] + 1, dp[i]);
}
}
}
return dp[amount] == (amount + 1) ? -1 : dp[amount];
}

void test() {
System.out.println(coinChange(new int[]{1, 2, 5}, 5));
System.out.println(coinChange(new int[]{1, 2, 5}, 10));
System.out.println(coinChange(new int[]{1, 2, 5}, 11));
System.out.println(coinChange(new int[]{2}, 3));
}
}
}