forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p031.java
33 lines (26 loc) · 776 Bytes
/
p031.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
/*
* Solution to Project Euler problem 31
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p031 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p031().run());
}
public String run() {
int total = 200;
int[] coins = {1, 2, 5, 10, 20, 50, 100, 200};
// Knapsack problem
int[][] ways = new int[coins.length + 1][total + 1];
ways[0][0] = 1;
for (int i = 0; i < coins.length; i++) {
for (int j = 0; j <= total; j++) {
for (int k = j; k <= total; k += coins[i])
ways[i + 1][k] += ways[i][j]; // Dynamic programming
}
}
return Integer.toString(ways[coins.length][total]);
}
}