-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCoinChange.java
More file actions
42 lines (34 loc) · 1.16 KB
/
CoinChange.java
File metadata and controls
42 lines (34 loc) · 1.16 KB
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
package com.company;
import org.junit.Test;
import java.util.HashMap;
public class CoinChange {
public static final int maxValue = 10000000;
public static HashMap<HashMap<Integer, Integer>, Integer> cache =
new HashMap<>();
public int coinChange(int[] coins, int amount) {
int res = search(0, amount, coins);
if (res < maxValue) {
return res;
} else {
return -1;
}
}
public int search(int index, int mAmount, int[] mCoins) {
if (mAmount == 0) return 0;
if (mAmount < 0) return maxValue;
if (index >= mCoins.length) return maxValue;
HashMap<Integer, Integer> hashMap = new HashMap<>();
hashMap.put(index, mAmount);
if (cache.containsKey(hashMap)) {
return cache.get(hashMap);
}
int a = 1 + search(index, mAmount - mCoins[index], mCoins);
int b = search(index + 1, mAmount, mCoins);
cache.put(hashMap, Math.min(a, b));
return Math.min(a, b);
}
@Test
public void test() {
System.out.println(coinChange(new int[]{2}, 3));
}
}