8000 adding CoinChange · LeetCode-Interview/interviews@6a4460a · GitHub
[go: up one dir, main page]

Skip to content

Commit 6a4460a

Kevin Naughton JrKevin Naughton Jr
authored andcommitted
adding CoinChange
1 parent 6830e7c commit 6a4460a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
2+
3+
//Example 1:
4+
//coins = [1, 2, 5], amount = 11
5+
//return 3 (11 = 5 + 5 + 1)
6+
7+
//Example 2:
8+
//coins = [2], amount = 3
9+
//return -1.
10+
11+
//Note:
12+
//You may assume that you have an infinite number of each kind of coin.
13+
14+
class CoinChange {
15+
public int coinChange(int[] coins, int amount) {
16+
if(amount < 1) {
17+
return 0;
18+
}
19+
20+
return coinChangeRecursive(coins, amount, new int[amount]);
21+
}
22+
23+
public int coinChangeRecursive(int[] coins, int amount, int[] dp) {
24+
if(amount < 0) {
25+
return -1;
26+
}
27+
if(amount == 0) {
28+
return 0;
29+
}
30+
if(dp[amount - 1] != 0) {
31+
return dp[amount - 1];
32+
}
33+
34+
int min = Integer.MAX_VALUE;
35+
for(int coin: coins) {
36+
int result = coinChangeRecursive(coins, amount - coin, dp);
37+
if(result >= 0 && result < min) {
38+
min = 1 + result;
39+
}
40+
}
41+
42+
dp[amount - 1] = min == Integer.MAX_VALUE ? -1 : min;
43+
return dp[amount - 1];
44+
}
45+
}

0 commit comments

Comments
 (0)
0