-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Problem31.java
47 lines (37 loc) · 1.37 KB
/
Problem31.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
/*
* File: Problem31.java
* ----------------------
* Finds the number of combinations to get a specified value.
*
* NOTE: Solution is not entirely my own. Modified from
* https://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
*/
import java.util.Arrays;
public class Problem31 {
public static void main(String args[]) {
// to calculate runtime of different methods
double startTime = System.nanoTime();
int coins[] = {1, 2, 5, 10, 20, 50, 100, 200};
int numOfCoins = coins.length;
int desiredValue = 200;
System.out.println(countWays(coins, numOfCoins, desiredValue));
double duration = (System.nanoTime() - startTime) / 1000000000;
System.out.println(duration + " seconds");
}
static long countWays(int coins[], int numOfCoins, int desiredValue) {
long[] table = new long[desiredValue + 1];
// Initialize all table values as 0
Arrays.fill(table, 0);
// Base case (If given value is 0)
table[0] = 1;
// Number of coins
for (int i = 0; i < numOfCoins; i++) {
// Each coin
for (int j = coins[i]; j <= desiredValue; j++) {
// Gets all previous values in an upwards tree
table[j] += table[j - coins[i]];
}
}
return table[desiredValue];
}
}