Skip to content
Advertisement

Wrong result if a recursive function is called twice successively with different parameters

I have this recursive function:

JavaScript

When I print this:

JavaScript

It shows -1, which is correct. But, when I print this:

JavaScript

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

To use your memo, you need pass it to the recursive calls

JavaScript

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement