forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp031.java
More file actions
38 lines (30 loc) · 1.09 KB
/
p031.java
File metadata and controls
38 lines (30 loc) · 1.09 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
/*
* Solution to Project Euler problem 31
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/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());
}
/*
* We use the standard dynamic programming algorithm to solve the subset sum problem over integers.
* The order of the coin values does not matter, but the values need to be unique.
*/
private static final int TOTAL = 200;
private static int[] COINS = {1, 2, 5, 10, 20, 50, 100, 200};
public String run() {
// ways[i][j] is the number of ways to use any copies of
// the first i coin values to form an unordered sum of j
int[][] ways = new int[COINS.length + 1][TOTAL + 1];
ways[0][0] = 1;
for (int i = 0; i < COINS.length; i++) {
int coin = COINS[i];
for (int j = 0; j <= TOTAL; j++)
ways[i + 1][j] = ways[i][j] + (j >= coin ? ways[i + 1][j - coin] : 0);
}
return Integer.toString(ways[COINS.length][TOTAL]);
}
}