I am fairly new to python, stumbled upon a dynamic programming course on youtube that I thought would help me better understand the concept @ here.
Now, I have been struggling to understand it... Would anyone have the time to explain the way this code works?
The function takes a target sum and an array of numbers as arguments. The function should return an array containing any combination of numbers that add up exactly to the target number.
def howSum(targetSum, numbers, memo = {}):
if targetSum in memo : return memo[targetSum]
if targetSum == 0 : return []
if targetSum < 0 : return None
for num in numbers:
remainder = targetSum - num
remainderResult = howSum(remainder, numbers, memo)
if remainderResult != None:
memo[targetSum] = [*remainderResult, num]
return memo[targetSum]
memo[targetSum] = None
return None
The original code was written for JS, I translated it to Python but I am struggling with a couple of things: namely:
return statements at the end of the definition
and this line specificaly:
memo[targetSum] = [*remainderResult, num]
Is there a concept I am missing?