-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoin Change.java
More file actions
70 lines (53 loc) · 1.82 KB
/
Coin Change.java
File metadata and controls
70 lines (53 loc) · 1.82 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
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public int coinChange(int[] coins, int amount) {
if(amount <= 0)return 0;
int[] dp = new int[amount + 1];
Arrays.fill(dp,-2);
Arrays.sort(coins);
coin(coins,amount,dp);
return dp[amount] == -1 ? -1 : dp[amount]; // Fixing incorrect return value
}
public int coin(int[] coins,int amount,int[] dp){
if(amount < 0)return -1;
if(amount == 0){
return 0;
}
if(dp[amount] != -2)return dp[amount];
int minSteps = Integer.MAX_VALUE;
for(int i=0;i<coins.length;i++){
int val = coin(coins,amount - coins[i],dp);
if(val >= 0){
minSteps = Math.min(minSteps,val + 1);
}
}
dp[amount] = (minSteps == Integer.MAX_VALUE) ? -1 : minSteps;
return dp[amount];
}
}
/////////////////////////////Recursion /(Not work)//////////////////////////////////
class Solution {
public int coinChange(int[] coins, int amount) {
if(amount <= 0)return 0;
int[] dp = new int[amount + 1];
Arrays.fill(dp,-1);
Arrays.sort(coins);
coin(coins,amount,dp);
return dp[amount] == -1 ? -1 : dp[amount]; // Fixing incorrect return value
}
public int coin(int[] coins,int amount,int[] dp){
if(amount < 0)return -1;
if(amount == 0){
return 0;
}
if(dp[amount] != -1)return dp[amount];
int minSteps = Integer.MAX_VALUE;
for(int i=0;i<coins.length;i++){
int val = coin(coins,amount - coins[i],dp);
if(val >= 0){
minSteps = Math.min(minSteps,val + 1);
}
}
dp[amount] = (minSteps == Integer.MAX_VALUE) ? -1 : minSteps; // Fixing return condition
return dp[amount];
}
}