Coin sums
Problem 31
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?
|
Go to the thread for problem 31 in the forum.
Download overview for problem 31.
见到这个题目我的第一感觉就是要用我的第一篇博文关于整数划分的一篇介绍:地址如下
http://blog.csdn.net/zhangzhengyi03539/article/details/40298397 解题思路一样
附上matlab代码和Python代码:
matlab包含三个函数
主函数:
clear;clc;
global t; % 需要划分的数
global p; % 记录符合条件划分次数
p=0;
t=200;
a=[];
func(a);
disp(‘最终划分种类数p=‘)
p
func函数
function f=func(a)
global t; % 需要划分的数
global p; % 记录符合条件划分次数
count=[1,2,5,10,20,50,100,200];
temp=mysum(a);
k=length(a);
if k>0 % 第一次进入递归函数进入else
result=min([t-temp count(a(k))]); % 确定本步接下来分配次数
else
result=t-temp;
end
result=find(count<=result,1,‘last‘);
for i=result:-1:1
b=[a i];
if mysum(b)==t % 符合输出条件的b输出
p=p+1;
else % 不符合输出条件的b递归
if mysum(b)<t
func(b);
end
end
end
mysum函数:
function sum=mysum(a)
count=[1,2,5,10,20,50,100,200];
sum=0;
k=length(a);
for i=1:k
sum=sum+count(a(i));
end
然后是Python代码:
from functools import reduce
def getvalue(key):
return {1:1,2:2,3:5,4:10,5:20,6:50,7:100,8:200}[key]
def func(a):
global p
if len(a)<2:
if len(a)==0:
result=8
else:
result=a[0]
else:
print(str(p)+‘ ‘+str(a[0]))
minb=reduce(min,map(getvalue,a))
result=min(t-sum(map(getvalue,a)),minb)
for i in range(1,9):
if getvalue(i)>result:
result=i-1
break
for i in range(result,0,-1):
b=a.copy()
b.append(i)
temp=sum(map(getvalue,b))
if temp==t:
p+=1
else:
if temp<t:
func(b)
p=0
t=200
a=[]
func(a)
print(p)