-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
52 lines (48 loc) · 1.41 KB
/
Solution.java
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 L322;
import java.util.Arrays;
class Solution {
public int coinChange(int[] coins, int amount) {
int max = amount + 1;
int[] dp = new int[amount + 1];
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.length; j++) {
if (coins[j] <= i) {
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
/**
* 动态规划
*
* @param coins
* @param amount
* @return
*/
public int coinChange2(int[] coins, int amount) {
int INF = (int) 1e9;
int[] opt = new int[amount + 1];
opt[0] = 0;
for (int i = 1; i <= amount; i++) {
opt[i] = INF;
for (int j = 0; j < coins.length; j++) {
if (i - coins[j] >= 0)
opt[i] = Math.min(opt[i], opt[i - coins[j]] + 1);
}
}
if (opt[amount] >= INF)
opt[amount] = -1;
return opt[amount];
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] coins = { 1, 2, 5 };
int amount = 11;
int ans = solution.coinChange(coins, amount);
int ans2 = solution.coinChange2(coins, amount);
System.out.println(ans + " " + ans2);
}
}