腾讯----硬币面值组合问题

题目描述
有n种不同面值的硬币,每种面值的硬币都有无限多个。为了方便携带,希望带尽量少的硬币,并且要能组合出1到m之间(包括1和m)的所有面值。
输入
第一行包含两个整数m, n,含义如题目所述。第二行包含n个整数,第i个整数表示第i种硬币的面值。
输出
输出一个整数,表示最少需要携带的硬币数量。如果无解,则输出-1。
示例
输入:
20 4
1 2 5 10
输出:
5

python解:

operator=list(map(int,input().split()))
m=operator[0] #最大面值
n=operator[1] #硬币种类
arr=list(map(int,input().split()))
arr=sorted(arr)
if arr[0]!=1:
    print(-1)
num=p=res=0
while num<m:
    while p+1<n and arr[p+1]<=num+1:
        p=p+1
    num+=arr[p]
    res+=1
print(res)

猜你喜欢

转载自blog.csdn.net/haoshan4783/article/details/89070130