|
1 | 1 | package code.algorithm.leetcode; |
2 | 2 |
|
3 | | -import java.util.Arrays; |
| 3 | +import org.springframework.util.Assert; |
4 | 4 |
|
5 | 5 | /** |
6 | | - * 〈一句话功能简述〉<p> |
| 6 | + * 〈零钱兑换〉<p> |
7 | 7 | * 〈功能详细描述〉 |
| 8 | + * 有1,2,5面值的硬币,现在有amount元,想兑换成硬币,最少需要多少枚硬币? |
| 9 | + * 递推方程: dp[i] = min(dp[i-1]+1, dp[i-2]+1, dp[i-5]+1) |
8 | 10 | * |
9 | 11 | * @author zixiao |
10 | 12 | * @date 2020/1/17 |
11 | 13 | */ |
12 | 14 | public class P322 { |
13 | 15 |
|
14 | | - public int coinChange(int[] coins, int amount) { |
15 | | - if(coins.length == 0 || amount == 0){ |
16 | | - return -1; |
| 16 | + public int coinChange(int[] coins, int amount){ |
| 17 | + int len = amount+1; |
| 18 | + int[] dp = new int[len]; |
| 19 | + dp[0] = 0; |
| 20 | + |
| 21 | + for (int i = 1; i <= amount; i++) { |
| 22 | + int min = len; |
| 23 | + for (int coin : coins){ |
| 24 | + if(i>=coin && dp[i-coin] != -1){ |
| 25 | + min = Math.min(min, dp[i-coin]+1); |
| 26 | + } |
| 27 | + } |
| 28 | + dp[i] = min == len ? -1 : min; |
17 | 29 | } |
18 | | - int maxIdx = coins.length-1; |
19 | | - Arrays.sort(coins); |
20 | | - int i = maxIdx; |
| 30 | + return dp[amount]; |
| 31 | + } |
21 | 32 |
|
22 | | - int num = 0; |
| 33 | + public static void main(String[] args) { |
| 34 | + P322 p322 = new P322(); |
| 35 | + System.out.println(p322.coinChange(new int[]{2}, 3)); |
23 | 36 |
|
24 | | - num += amount/coins[i]; |
25 | | - amount = amount%coins[i]; |
| 37 | + System.out.println(p322.coinChange(new int[]{1, 2, 5}, 5)); |
| 38 | + System.out.println(p322.coinChange(new int[]{1, 2, 5}, 9)); |
| 39 | + Assert.isTrue(p322.coinChange(new int[]{186,419,83,408}, 6249)==20, ""); |
26 | 40 |
|
27 | | - return num; |
| 41 | + //System.out.println(p322.coinChange(new int[]{2}, Integer.MAX_VALUE)); |
28 | 42 | } |
29 | 43 |
|
30 | 44 | } |
0 commit comments