Skip to content

Commit 757626b

Browse files
committed
feat: solved 322
1 parent bcfd590 commit 757626b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.fghpdf.CoinChange;
2+
3+
/**
4+
* @author fghpdf
5+
* @date 2019/12/29
6+
* https://leetcode.com/problems/coin-change/
7+
* dp coins [1,2,5] amount 11
8+
* dp[0] is 0
9+
* dp[1] is 1. coin 1
10+
* dp[2] is 1. coin 2. min(coin 2 + dp[0]...coin 1 + dp[1])
11+
* ...
12+
* dp[11] is 3. min(coin 5 + dp[6]...coin 3 + dp[8]...coin 1 + dp[10])
13+
**/
14+
public class Solution {
15+
public int coinChange(int[] coins, int amount) {
16+
if (amount < 1) {
17+
return amount;
18+
}
19+
return helper(coins, amount, new int[amount]);
20+
}
21+
22+
private int helper(int[] coins, int rem, int[] dp) {
23+
if (rem < 0) {
24+
return -1;
25+
}
26+
27+
if (rem == 0) {
28+
return 0;
29+
}
30+
31+
if (dp[rem - 1] != 0) {
32+
return dp[rem - 1];
33+
}
34+
35+
int min = Integer.MAX_VALUE;
36+
for (int coin : coins) {
37+
int res = helper(coins, rem - coin, dp);
38+
if (res >= 0 && res < min) {
39+
min = res + 1;
40+
}
41+
}
42+
dp[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
43+
return dp[rem - 1];
44+
}
45+
46+
public static void main(String[] args) {
47+
Solution solution = new Solution();
48+
System.out.println(solution.coinChange(new int[]{1, 2, 5}, 11));
49+
}
50+
}

0 commit comments

Comments
 (0)