您的位置:首页 > 编程语言 > Java开发

Java 欧拉工程 第三十一篇【考察英国货币面值的组合问题】

2014-09-04 12:09 176 查看
题目:

在英国,货币是由英镑£,便士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的方法?

原题:
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?
解题思路:
这道题算是经典的背包问题了,我一开始想到的思路就是每个数字一个for,循环个7、8次遍历之和得到答案,不过细想觉得这样的算法实在太笨,百度一下,发现大多数的技术博客都用的这种本办法,么办法,我只好再google,不得不说老外在算法确实很有效率,用的是动态规划的思想,通过大题化小求最优解
首先由于参与求和的硬币只有8个,所以只有8种情况,使用硬币1;1,2;1,2,5;。。。。总计8种,
target 1 2 3 4 5
ways
1 2 2 3 3
public class Launcher {

public static void main(String[] args) {
int coins[]={1,2,5,10,20,50,100,200};
int  total=200;
int[] matrix = new int[total+1];
matrix[0]=1;

for(int i=0;i<coins.length;i++ ){
for(int j=coins[i];j<matrix.length;j++){
matrix[j]+=matrix[j-coins[i]];
}
}
System.out.println(matrix[200]);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: