硬币最小数量
题目描述
Description
Given the list of coins of distinct denominations and total amount of money. Output the minimum number of coins required to make up that amount. Output -1 if that money cannot be made up using given coins. You may assume that there are infinite numbers of coins of each type.
Input
The first line contains ‘T’ denoting the number of test cases. Then follows description of test cases. Each cases begins with the two space separated integers ‘n’ and ‘amount’ denoting the total number of distinct coins and total amount of money respectively. The second line contains N space-separated integers A1, A2, …, AN denoting the values of coins.
Constraints:1<=T<=30,1<=n<=100,1<=Ai<=1000,1<=amount<=100000
Output
Print the minimum number of coins required to make up that amount or return -1 if it is impossible to make that amount using given coins.
Sample Input 1
2
3 11
1 2 5
2 7
2 6
Sample Output 1
3
-1
题目解析
给你一个目标钱数,和硬币的一个面值列表,问你能不能用最少的硬币去刚刚好凑成目标钱数
本题硬币是无限枚的
eg 凑成11元, 有1 2 5三种类型的硬币,一种一个就正好凑够了,答案为3
思路解析
每次尽可能选择最大的面值,直到该面值不能选取后,再去选下一个面值,重复直到选完或者不能选了为止
但这种方法虽然能通过,但是解这道题有一个问题,请看这个用例
2 8
2 5
即:有8块钱, 有2元和5元的硬币,按照贪心逻辑会无法刚刚选够,因此会输出-1
硬币问题能否使用贪心方法去解取决于硬币的面值组成
这道题期末考了,没过...
代码实现
python
if __name__ == '__main__':
for i in range(int(input())):
num, total = list(map(int, input().split(" ")))
coin_arr = list(set(map(int, input().split(" "))))
coin_arr.sort(reverse=True)
count = 0
i = 0
while i < len(coin_arr):
if total - coin_arr[i] >= 0:
total = total - coin_arr[i]
count += 1
if total == 0:
break
else:
i += 1
if total == 0:
print(count)
else:
print(-1)