-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathCoinChange.java
More file actions
69 lines (59 loc) · 1.66 KB
/
CoinChange.java
File metadata and controls
69 lines (59 loc) · 1.66 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
// Time Complexity : O(m*n)
// Space Complexity : O(m*n)
// Did this code successfully run on Leetcode :yes.
// Any problem you faced while coding this :
// Your code here along with comments explaining your approach
public class CoinChange {
// Time c omplexity O(m x n)
// space complexity O(m x n)
public int coinChange(int[] coins, int amount) {
// edge case
if (coins == null || coins.length == 0)
return 0;
int[][] dp = new int[coins.length + 1][amount + 1]; // because of 0
for (int i = 1; i < dp[0].length; i++)
dp[0][i] = 9999;
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (j < coins[i - 1]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - coins[i - 1]] + 1);
}
}
}
int result = dp[dp.length - 1][dp[0].length - 1];
if (result >= 9999)
return -1;
return result;
}
/*
*
// Time c omplexity O(m x n)
// space complexity O(m x n)
*
public int coinChange(int[] coins, int amount) {
int m= coins.length, n=amount;
int [][] dp= new int[m+1][n+1];
dp[0][0]=0;
// top row
for (int j=1; j<=n;j++){
dp[0][j]=Integer.MAX_VALUE-2;
}
for (int i=1; i<=m;i++){
for (int j=1; j<=n;j++){
if (j<coins[i-1]){
//not choose case
dp[i][j]=dp[i-1][j];
}else{
dp[i][j]=Math.min(dp[i-1][j],1+dp[i][j-coins[i-1]]);
}
}
}
int resp=dp[m][n];
if (resp>=Integer.MAX_VALUE-2)
return -1;
return resp;
}
*/
}