forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoin Change.java
More file actions
57 lines (55 loc) · 1.46 KB
/
Coin Change.java
File metadata and controls
57 lines (55 loc) · 1.46 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public int coinChange(int[] coins, int amount) {
Integer[] dp = new Integer[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (i - coin < 0) {
continue;
}
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
return dp[amount] == (amount + 1) ? -1 : dp[amount];
}
private int coinChangeMemoization(int[] coins, int amount, Integer[] memo) {
if (amount < 0) {
return -1;
}
if (amount == 0) {
return 0;
}
if (memo[amount] != null) {
return memo[amount];
}
int minCount = Integer.MAX_VALUE;
for (int coin : coins) {
int count = coinChangeMemoization(coins, amount - coin, memo);
if (count == -1) {
continue;
}
minCount = Math.min(minCount, count + 1);
}
memo[amount] = minCount == Integer.MAX_VALUE ? -1 : minCount;
return memo[amount];
}
// This approach times out due to overlapping subproblems
private int coinChangeRecursive(int[] coins, int amount) {
if (amount < 0) {
return -1;
}
if (amount == 0) {
return 0;
}
int minCount = Integer.MAX_VALUE;
for (int coin : coins) {
int count = coinChangeRecursive(coins, amount - coin);
if (count == -1) {
continue;
}
minCount = Math.min(minCount, count);
}
return minCount == Integer.MAX_VALUE ? -1 : minCount;
}
}