美文网首页
硬币最小数量

硬币最小数量

作者: loick | 来源:发表于2019-11-28 13:02 被阅读0次

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.

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
2
3 11
1 2 5
2 7
2 6
Sample Output
3
-1

思路

动态规划,变成小问题递归求解

如果有硬币[1, 2, 5], 总量11

从上到下的动态规划:

选取0个1, 递归[2, 5], 11;选取一个1,递归[2, 5], 10; 或者选2个1,递归[2, 5], 9.......

递归结束条件是当前只有一个硬币的时候,判断总量是否能整除硬币面值,如果能返回数量,不然返回-1或者其他“不正常”的值。

需要注意的是,从上到下的方式很多时候可能是重复调用,比如上面的例子,选取一个1,一个2,递归[5], 8; 和选取三个1,0个2,递归[5], 8是一样的。为了避免重复调用,可以使用一个map记录调用的参数信息,如果调用过,直接返回结果。这里递归的硬币就可以使用当前硬币在数组中的位置参数index。

python
import functools
def solve(coins, amount):
    @functools.lru_cache(None)
    def dp(i, amount):
        if amount == 0:
            return 0
        if i == 0:
            return [float('inf'), amount // coins[0]][amount % coins[0] == 0]

        ans = float('inf')
        for j in range(amount//coins[i] + 1):
            ans = min(ans, j + dp(i-1, amount-coins[i]*j))
        return ans

    res = dp(len(coins)-1, amount)
    return [res, -1][res == float('inf')]


for _ in range(int(input())):
    _, amount = map(int, input().split())
    coins = list(map(int, input().split()))
    print(solve(coins, amount))

相关文章

  • 硬币最小数量

    Description Given the list of coins of distinct denominat...

  • Java硬币找零问题

    假如有硬币1,3,5如何用最少的硬币数量找回11元,硬币可复用 要得到1元需要的硬币个数n=f(1) = f(0)...

  • 2019字节跳动春招笔试题

    动态规划-最小硬币 数值最少由多少个硬币组成 字符串 lloo 去掉 o 成 llo AABBCC 去掉 B 成 ...

  • 换硬币 -dp

    换硬币 给出不同面额的硬币以及一个总金额. 写一个方法来计算给出的总金额可以换取的最少的硬币数量. 如果已有硬币的...

  • 动态规划 凑硬币问题

    凑硬币问题 假设有 1 元,3 元,5 元的硬币若干(无限),现在需要凑出 11 元,问如何组合才能使硬币的数量最...

  • 最小硬币找零问题

    最小硬币找零问题是硬币找零问题的一个变种。硬币找零问题是给出要找零的钱数,以及可以用的硬币面额d1...dn及其数...

  • 【LeetCode】硬币-官方题解学习

    题目及其链接如下: #面试题8-11 硬币 题目:硬币。给定数量不限的硬币,币值为25分、10分、5分和1分,编写...

  • 每日leetcode 面试题 08.11 2020-03-19

    面试题 08.11. 硬币 硬币。给定数量不限的硬币,币值为25分、10分、5分和1分,编写代码计算n分有几种表示...

  • 硬币问题-动态规划

    问题描述 假设有 1 元,3 元,5 元的硬币若干(无限),现在需要凑出 11 元,问如何组合才能使硬币的数量最少...

  • 记录自己一个自定义的购物车加减控件

    自定义一个购物车加减控件,可以加减数量,可以编辑数量,可以设置数量最大值(库存数量)最小值(最少购买数量) 布局文...

网友评论

      本文标题:硬币最小数量

      本文链接:https://www.haomeiwen.com/subject/pnxbwctx.html