简体   繁体   中英

Combination Sum python recursion scope

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?

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM