I was solving target sum problem on leetcode which asks us to use either +/- symbol on all integers and then check sum of array is equal to target. I'm trying to return all possible combinations using this symbols using recursion This is my current code which works but is not optimized
nums=[1,1,1]
res=[]
def recursion(i,temp,res):
if i==len(nums):
res.append(temp[:])
return
temp.append(nums[i])
recursion(i+1,temp,res)
temp.pop()
temp.append(-1*nums[i])
recursion(i+1,temp,res)
temp.pop()
recursion(0,[],res)
print(res)
Result of this program is: [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]] Can someone please help me to understand how can I memoize it?