1

I implemented a combination sum algorithm to the following problem:

# Given an array: [10,1,2,7,6,1,5]
# and a target: 8
# Find the solution set that adds up to the target
# in this case:
# [1, 7]
# [1, 2, 5]
# [2, 6]
# [1, 1, 6]

def cominbationSum(arr, target):
    arr =sorted(arr)
    res = []
    path = []
    dfs_com(arr, 0, target, path, res)
    return res

def dfs_com(arr, curr, target, path, res):
    if target == 0:
        res.append(path)
        return
    if target < 0:
        return
    for i in range(curr, len(arr)):
        if i > curr and arr[i] == arr[i-1]: # skip duplicates
            continue
        path.append(arr[i])
        dfs_com(arr, i+1, target - arr[i], path, res)
        path.pop(len(path)-1)


print cominbationSum([10,1,2,7,6,1,5], 8)

My algorithm generates the proper combinations, but it has a problem returning res. It returns res as [[],[],[],[]] rather than [[1, 1, 6],[1, 2, 5],[1, 7],[2, 6]]. Any idea why path isn't appending to res properly?

2
  • What's the python version? Commented Mar 15, 2016 at 19:39
  • @Kasramvd python 2.7 Commented Mar 15, 2016 at 20:14

2 Answers 2

4

Looks like a reference issue. Try:

if target == 0:
    res.append(path[:])
    return

This will create a shallow copy of path, so any pop performed on path later in the code will have no effect on the lists inside res.

Sign up to request clarification or add additional context in comments.

Comments

1

Change the line

res.append(path)

to

res.append(path[:])

so you are getting a copy of path instead of the path itself. The problem is because you are removing elements in this line:

path.pop(len(path)-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.