recursively implementing 'minimum number of coins' in python

前端 未结 5 1356
一整个雨季
一整个雨季 2021-01-21 02:01

This problem is same as asked in here.

Given a list of coins, their values (c1, c2, c3, ... cj, ...), and the total sum i. Find the minimum number of coins the sum

5条回答
  •  日久生厌
    2021-01-21 02:32

    Like the comment says, you need to return a big enough value when i < 0, so that it won't get selected by your min like this:

    cdict = {}
    def C(i, coins):
    
        if i == 0:
            return 0
    
       if i < 0:
            return 1e100    # Return infinity in ideally
    
        if i in cdict:
            return cdict[i]
        else:
            answer = 1 + min([C(i - cj, coins) for cj in coins])
            cdict[i] = answer
        return answer
    

    now whenever the function returns 1e100, it means solution is not possible.

    for example:

    $ python2 coins.py 13555 1 5 9
    1507  coins
    $ python2 coins.py 139 1 5 9
    19  coins
    $ python2 coins.py 139  5 9
    19  coins
    $ python2 coins.py 13977  5 9
    1553  coins
    $ python2 coins.py 13977   9
    1553  coins
    $ python2 coins.py 139772   9
    1e+100  coins
    

    with usage:

    python2 coins.py    ...
    

提交回复
热议问题