Combination Sum code giving me incorrect answer

143 Views Asked by At

Problem (Combination Sum): 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.

I'm not being able to figure out what's going wrong with the recursion here. Currently it is not printing out even a single subsequence. I know there are other, better methods to solve this problem but I need help figuring out what is wrong with my code as I'm trying to learn the fundamentals of recursion and backtracking.

def combinationSum(arr, i, target, tempSum, tempList):
    if i == len(arr) or tempSum >= target:
        if tempSum == target and i == len(arr): # Required answer will have sum==target and it would have traversed the whole list
            print(tempList)
        return

    # Case 1: Go to the next array element
    combinationSum(arr, i+1, target, tempSum, tempList.copy())

    # Case 2: Stay on the current array element and add it to the tempList
    tempSum += arr[i]
    tempList.append(arr[i])
    combinationSum(arr, i, target, tempSum, tempList.copy())

combinationSum([1, 2, 3], 0, 6, 0, [])

Expected answer:

[3, 3]
[2, 2, 2]
[1, 2, 3]
[1, 1, 2, 2]
[1, 1, 1, 3]
[1, 1, 1, 1, 2]
[1, 1, 1, 1, 1, 1]
1

There are 1 best solutions below

0
Rituparna Warwatkar On

You need to remove one condition and i == len(arr) so that it becomes

def combinationSum(arr, i, target, tempSum, tempList):
    if i == len(arr) or tempSum >= target:
        if tempSum == target: # Required answer will have sum==target and it would have traversed the whole list
            print(tempList)
        return

    # Case 1: Go to the next array element
    combinationSum(arr, i+1, target, tempSum, tempList.copy())

    # Case 2: Stay on the current array element and add it to the tempList
    tempSum += arr[i]
    tempList.append(arr[i])
    combinationSum(arr, i, target, tempSum, tempList.copy())

combinationSum([1, 2, 3], 0, 6, 0, [])

it is not always necessary that when the combination is formed, the index pointer should move out of the array. For example, take the case of [1,1,1,1,1,1], the index pointer is still on 0th index and the combination is formed too. In this case even if the target is achieved, and pointer is not out of the array, the list wont be printed.