forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT4.java
More file actions
36 lines (34 loc) · 905 Bytes
/
Copy pathT4.java
File metadata and controls
36 lines (34 loc) · 905 Bytes
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
/**
* @program JavaBooks
* @description: 零钱兑换
* @author: mf
* @create: 2020/04/15 17:35
*/
package subject.dp;
/**
* 输入: coins = [1, 2, 5], amount = 11
* 输出: 3
* 解释: 11 = 5 + 5 + 1
* 输入: coins = [2], amount = 3
* 输出: -1
*/
public class T4 {
public int coinChange(int[] coins, int amount) {
// 初始化bp
int[] dp = new int[amount + 1];
for (int i = 0; i < amount; i++) {
dp[i] = -1;
}
dp[0] = 0; // 金额0的最优解
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.length; j++) {
if (i - coins[j] >= 0 && dp[i - coins[j]] != -1) {
if (dp[i] == -1 || dp[i] > dp[i - coins[j]] + 1) {
dp[i] = dp[i - coins[j]] + 1;
}
}
}
}
return dp[amount];
}
}