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
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 ...