0

`

class Solution:
    def path(self, m: int, n: int, dp: dict = {}) -> int:
        if m == 1 or n == 1:
            return 1
        
        key = f"{m}:{n}"
        if key not in dp.keys():
            dp[key] = self.path(m - 1, n) + self.path(m, n - 1)
        return dp[key]
    
    def uniquePaths(self, m: int, n: int) -> int:
        return self.path(m, n)

`

This is my code, my doubt is, I am not passing dp variable in the recursion call still dp storing values.

By mistake, I forget to pass dp as an argument, and when I realized I pass the variable and the behavior of the code is identical.

I don't understand how dp variable is able to store the values when it is not being passed in the recursion call?

I was expecting the code will work like normal recursion code, but not as a Dynamic Problem, but it is working as a Dynamic Problem, How?

Yash Jain
  • 1
  • 1
  • 1
    What i can see is that `dp` is an optional parameter to your `path()`. So, if no value is defined by default the method is going to assume a blank dictionary for it. – vikscool Nov 02 '22 at 07:22
  • @vikscool That's just not what is happening, you *won't* get a new empty dict, see the duplicate. – Thierry Lathuille Nov 02 '22 at 07:28
  • @vikscool yes ```dp``` variable is an optional parameter. Still, how ```dp``` is getting the value later in recursion if we are not passing it, bcoz then in every recursion it will create a new ```dp``` variable that does not hold the previous values, also this is a dynamic program without passing ```dp``` variable as a parameter to the recursion call. – Yash Jain Nov 09 '22 at 07:25

0 Answers0