Skip to content

Commit 1a51455

Browse files
committed
add: MinCoinCombinationTopDown, use target + 1 to replace float('inf') in python, since Integer.MAX_VALUE will lead to overflow in the question. Alternative is to check topDownDp return value before add 1 in 1 + topDownDp(coins, target - coin, memo)
1 parent b913528 commit 1a51455

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class MinCoinCombinationTopDown {
5+
int max;
6+
7+
public int minCoinCombinationTopDown(int[] coins, int target) {
8+
max = target + 1;
9+
int res = topDownDp(coins, target, new HashMap<>());
10+
return res == max ? -1 : res;
11+
}
12+
13+
private int topDownDp(int[] coins, int target, Map<Integer, Integer> memo) {
14+
// Base case: if the target is 0, then 0 coins are needed to reach
15+
// it.
16+
if (target == 0) {
17+
return 0;
18+
}
19+
if (memo.containsKey(target)) {
20+
return memo.get(target);
21+
}
22+
// Initialize 'minCoins' to a large number.
23+
int minCoins = max;
24+
for (int coin : coins) {
25+
// Avoid negative targets.
26+
if (coin <= target) {
27+
// Calculate the minimum number of coins needed if we use
28+
// the current coin.
29+
minCoins = Math.min(minCoins, 1 + topDownDp(coins, target - coin, memo));
30+
}
31+
}
32+
memo.put(target, minCoins);
33+
return memo.get(target);
34+
}
35+
}

0 commit comments

Comments
 (0)