In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
在英国,货币是由英镑£,便士p构成的。一共有八种钱币在流通:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) 和 £2 (200p).
要构造£2可以用如下方法:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
允许使用任意数目的钱币,一共有多少种构造£2的方法?
package com.fk.euler;
/**
* Created by fengkai on 1/14/17.
*/
public class Euler31 {
public static void main(String[] args) {
int[] coin = {200,100, 50, 20, 10, 5, 2, 1};
int target = 200;
System.out.println(getCoint(coin, target, coin[0]));
}
private static int getCoint(int[] coin, int target, int c) {
if (c == 1) {
return 1;
}
if (target == 0) {
return 1;
}
int max = target / c;
int sum = 0;
for (int i = 0; i <= max; i++) {
int nextc = 1;
for (int j = 0; j < coin.length; j++) {
if (c == coin[j] && c != 1) {
nextc = coin[j + 1];
break;
}
}
sum += getCoint(coin, target - i * c, nextc);
}
return sum;
}
}
思路有多种,具体吧官网文档放上吧,我写的是第一个种。