4

I wrote a recursion function to get all subsets out of a list of integers. For example, given a list [1, 2, 3], the return will be [[],[1],[2],[3],[1, 2],[1, 3],[2, 3],[1, 2, 3]].

Here is my code:

def subsets(nums):

    def helper(subset, i):

        if i == len(nums):
            print('return = ', subset)
            res.append(subset)

        else:
            helper(subset, i+1)
            subset.append(nums[i])
            helper(subset, i+1)
            subset.remove(nums[i])

    res = []
    helper([], 0)
    return res

I print out the subset in each recursion and they are right. However, the final return res is always empty.

return =  []
return =  [3]
return =  [2]
return =  [2, 3]
return =  [1]
return =  [1, 3]
return =  [1, 2]
return =  [1, 2, 3]
res = [[], [], [], [], [], [], [], []]

Anyone knows why? Appreciate it!

1

1 Answer 1

7

Pretty close! The issue is that subset is being appended to res, but later modified. What you want is a "frozen" version of what subset is then, not a "reference" to what it will eventually be.

So instead of res.append(subset), consider appending a copy of the list, for example with:

res.append(subset[:])

And you'll get your expected result:

[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, @jedwards!

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.