1 //70%
2 class Solution {
3 public int coinChange(int[] coins, int amount) {
4 if(amount == 0) return 0;
5 int[]res = new int[amount + 1];
6 for(int i = 0; i <= amount; i++) {
7 res[i] = Integer.MAX_VALUE;
8 }
9 /**
10 * 下面不用也可以
11 */
12 for(int i = 0; i < coins.length; i++) {
13 if(coins[i] <= amount) { //coin超过amount没有用,也会超过res的bound 所以不用赋值
14 res[coins[i]] = 1;
15 }
16 }
17 for(int j = 1; j <= amount; j++) {
18 if(res[j] == 1) continue;
19 for(int i = 0; i < coins.length; i++) {
20 if(coins[i] < j && res[j - coins[i]] != -1) {
21 res[j] = Math.min(res[j], res[j - coins[i]] + 1);
22 }
23 }
24 if(res[j] == Integer.MAX_VALUE) res[j] = -1;
25 }
26
27 return res[amount];
28 }
29 }
30
31
32 //30%
33
34 class Solution {
35 public int coinChange(int[] coins, int amount) {
36 if(amount == 0) return 0;
37 int[]res = new int[amount + 1];
38 for(int i = 0; i <= amount; i++) {
39 res[i] = Integer.MAX_VALUE;
40 }
41 res[0] = 0;
42 for(int j = 1; j <= amount; j++) {
43 for(int coin : coins) {
44 if(coin <= j && res[j - coin] != -1) {
45 res[j] = Math.min(res[j], res[j - coin] + 1);
46 }
47 }
48 if(res[j] == Integer.MAX_VALUE) res[j] = -1;
49 }
50
51 return res[amount];
52 }
53 }