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!
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With