I am new to programming and currently practicing the Leetcode questions. I am solving one of the questions using backtracking with memoization. The algorithm is not hard to understand, my code looks like this:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
def recursiveWithMem(S, i) -> int:
if i == len(nums):
return (1 if S == 0 else 0)
key = (i, S)
if key in mem:
return mem[key]
r = recursiveWithMem(S - nums[i], i + 1) + recursiveWithMem(S + nums[i], i + 1)
mem[key] = r
return r
mem = {}
return recursiveWithMem(S, 0)
When I look at other people's submissions they pass the mem as an attribute of the function. It doesn't affect the time complicity, but the second method uses 15MB memory and I implementation uses 35MB.
def findTargetSumWays(self, nums: List[int], S: int) -> int:
def recursiveWithMem(S, i, mem) -> int:
if i == len(nums):
return (1 if S == 0 else 0)
key = (i, S)
if key in mem:
return mem[key]
r = recursiveWithMem(S - nums[i], i + 1, mem) + recursiveWithMem(S + nums[i], i + 1, mem)
mem[key] = r
return r
mem = {}
return recursiveWithMem(S, 0, mem)
I also tried @cache, it uses 45MB of memory. I am very confused why passing memo into the function can help reduce memory use. Please help! Thank you in advance!