Given a set of candidate numbers A and a target number B, find all unique combinations in A where the candidate numbers sums to B. The same repeated number may be chosen from A unlimited number of times. code example
Example: Given a set of candidate numbers A and a target number B, find all unique combinations in A where the candidate numbers sums to B. The same repeated number may be chosen from A unlimited number of times.
def combinationSum(arr, sum):
ans = []
temp = []
arr = sorted(list(set(arr)))
findNumbers(ans, arr, temp, sum, 0)
return ans
def findNumbers(ans, arr, temp, sum, index):
if(sum == 0):
ans.append(list(temp))
return
for i in range(index, len(arr)):
if(sum - arr[i]) >= 0:
temp.append(arr[i])
findNumbers(ans, arr, temp, sum-arr[i], i)
temp.remove(arr[i])
arr = [2, 4, 6, 8]
sum = 8
ans = combinationSum(arr, sum)