I have this recursive function:
JavaScript
x
13
13
1
def coinChange(coins, amount: int, minimum = float('inf'), memo={}) -> int:
2
if amount in memo: return memo[amount]
3
4
if amount < 0: return -1
5
if amount == 0: return 0
6
for coin in coins:
7
x = coinChange(coins, amount - coin, minimum - 1, memo)
8
minimum = min(x, minimum) if x != -1 else minimum
9
if minimum == 0: break
10
11
memo[amount] = -1 if minimum == float('inf') else minimum + 1
12
return -1 if minimum == float('inf') else minimum + 1
13
When I print this:
JavaScript
1
2
1
print(coinChange([2], 3)) #-1
2
It shows -1
, which is correct.
But, when I print this:
JavaScript
1
3
1
print(coinChange([1,2,5], 11)) #3
2
print(coinChange([2], 3)) #the correct answer is -1 but it's showing 2
3
It shows 3
then 2
.
As you can see, the result of print(coinChange([2], 3))
weirdly changed from -1
to 2
.
The memo
is the reason for causing that wrong answer. But I don’t know how to update the function so that memo is re-initiated before each first call of coinChange
, and I don’t want to do it manually like this: print(coinChange([2], 3, memo = {}))
.
Advertisement
Answer
The issue you mention isn’t given with the code you share because of the following
JavaScript
1
2
1
x = coinChange(coins, amount - coin, minimum - 1, memo={})
2
To use your memo, you need pass it to the recursive calls
JavaScript
1
2
1
x = coinChange(coins, amount - coin, minimum - 1, memo=memo)
2
Effectivly you shouldn’t use a mutable object as default variable, because multiple calls will share the same instance, the issue is to use a None
JavaScript
1
5
1
def coinChange(coins, amount: int, minimum=float('inf'), memo=None) -> int:
2
if memo is None:
3
memo = {}
4
5