I'm writing codes to solve this problem, below are my codes, somehow I see the result is correct till the end of the for loop, but after the function returns it doesn't carry out the correct result value, see below the log print, anybody could help with it? Thanks!
https://leetcode.com/problems/coin-change/
"""
sort the coins to start with coin that has largest value;
then loop through possible number of that coins we could put,
and use dfs to go through other possible coin types
"""
def coinChange(self, coins, amount):
# write your code here
coins.sort()
coins=coins[::-1]
n=len(coins)
res=100000000000000
def getcom(i, coins, amount,count, res):
if amount==0:
res=min(res, count)
print("res: ", res)
if i==n:
return
coin=coins[i]
print("coin:", coins[i])
k=amount//coin
print("k:", k)
for j in range(k, -1, -1):
if count+j>res:
break
getcom(i+1, coins, amount-k*coin, count+k, res)
getcom(0,coins, amount, 0,res)
return res
testcase:Input: coins = [1, 2, 5], amount = 11
should Output: 3
Explanation: 11 = 5 + 5 + 1
my stdout
coin: 5
k: 2
coin: 2
k: 0
coin: 1
k: 1
res: 3
res: 3
coin: 2
k: 0
coin: 1
k: 1
res: 3
res: 3
coin: 2
k: 0
coin: 1
k: 1
res: 3
res: 3
----------
my output: 100000000000000