-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-518-Coin-Change-2.java
92 lines (76 loc) · 2.28 KB
/
LeetCode-518-Coin-Change-2.java
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Solution {
// DP: no optimization
/**
dp:
[1, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1]
[1, 1, 2, 2, 3, 3]
[1, 1, 2, 2, 3, 4]
Time Complexity: O(N * amount^2)
Time: 130 ms
*/
// public int change(int amount, int[] coins) {
// int N = coins.length;
// // sub problem
// int[][] dp = new int[N + 1][amount + 1];
// for (int i = 0; i <= N; i++) dp[i][0] = 1;
// for (int i = 1; i <= N; i++) {
// for (int j = 1; j <= amount; j++) {
// for (int k = 0; k * coins[i - 1] <= j; k++) {
// dp[i][j] += dp[i - 1][j - k * coins[i - 1]];
// }
// }
// }
// // printArray(dp);
// return dp[N][amount];
// }
private void printArray(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(Arrays.toString(arr[i]));
}
}
// DP: optimize time
/**
dp:
[1, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1]
[1, 1, 2, 2, 3, 3]
[1, 1, 2, 2, 3, 4]
Time Complexity: O(N * amount)
Time: 17 ms
*/
// public int change(int amount, int[] coins) {
// int N = coins.length;
// // sub problem
// int[][] dp = new int[N + 1][amount + 1];
// for (int i = 0; i <= N; i++) dp[i][0] = 1;
// for (int i = 1; i <= N; i++) {
// for (int j = 1; j <= amount; j++) {
// dp[i][j] = dp[i - 1][j];
// if (j >= coins[i - 1]) dp[i][j] += dp[i][j - coins[i - 1]];
// }
// }
// // printArray(dp);
// return dp[N][amount];
// }
// DP: optimize space
/**
dp:
[1, 1, 2, 2, 3, 4]
Time Complexity: O(N * amount)
Time: 5ms
*/
public int change(int amount, int[] coins) {
int N = coins.length;
// sub problem
int[] dp = new int[amount + 1];
dp[0] = 1;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= amount; j++) {
if (j >= coins[i - 1]) dp[j] += dp[j - coins[i - 1]];
}
}
// System.out.println(Arrays.toString(dp));
return dp[amount];
}
}