Quiz 39. Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
ex) [2,3,5] , 8 -> [2,2,2,2], [2,3,3], [3,5]
I wrote python code for this quiz using depth-first-algorithm recursively and that is similar to correct answer, but little bit different. And what I've written doesn't work correctly. There is just one part difference between mine and correct answer and I cannot find why mine is wrong.
def combinationSum(candidates, target: int): # cnadidates : [2,3,5], target = 8
result = []
def dfs(index : int, path : list, remain : int):
if remain < 0: # failed to find, prune this path!
return
if remain == 0: # successed!
result.append(path)
return
''' my code - wrong
path += [candidates[index]]
remain -= candidates[index]
for i in range(index, len(candidates)):
dfs(i, path, remain)
'''
''' correct answer
for i in range(index, len(candidates)):
dfs(i, path + [candidates[i]], remain - candidates[i])
'''
dfs(0, [], target)
return result
r = combinationSum([2,3,5] , 8)
print(r)
your code has several problems:
+= change the list in-place, it is very different from path+[something]
. While possible, it is usually undesirable in recursive calls.
Your code always minus candidates[index]
while the correct answer dynamically minus candidates[i]