I've been racking my brain trying to figure out why these two approaches in solving a Leetcode problem (Combination Sum), despite looking virtually the same. The first approach (working) takes in extra parameters that do not appear to be necessary. I have checked my code with print statements, and subsets with the required total are found, but for some reason, the result is not properly appended to res. Instead of appending the valid subset, it appends an empty list. I'm sure the answer is simple, but I cannot seem to find the logical difference. Here's both methods:
def combinationSumWorking(candidates, target):
result = []
def combinationUtil(index, numbers, sumSoFar):
if sumSoFar > target:
return
if sumSoFar == target:
#print("working",numbers)
result.append(numbers)
return
for i in range(len(candidates)):
combinationUtil(i, numbers+[candidates[i]], sumSoFar+candidates[i])
combinationUtil(0,[],0)
return result
def combinationSumMine(candidates, target):
res = []
def findCombos(subset):
if(sum(subset) > target):
subset = []
return
if(sum(subset) == target):
res.append(subset)
#print("mine",subset)
subset = []
return
for i in range(len(candidates)):
subset.append(candidates[i])
findCombos(subset)
subset.pop()
findCombos([])
return res
print(combinationSumMine([2,3,6,7],7))
print(combinationSumWorking([2,3,6,7],7))
The result is:
[[], [], [], []]
[[2, 2, 3], [2, 3, 2], [3, 2, 2], [7]]
rescould result in an empty list.