I am trying to implement a Python solution to program the search for all subsets in an integer array. I have to return an array that contains all subsets of the integer array without duplicates and sorted.
def subsetHelper(cur_set, index, A, ans):
if index >= len(A):
print "appending ", cur_set
ans.append(cur_set)
print "ans: ", ans
return
subsetHelper(cur_set, index+1, A, ans)
cur_set.append(A[index])
subsetHelper(cur_set, index+1, A, ans)
cur_set.pop()
def subsets(A):
A.sort()
ans = []
cur_set = []
subsetHelper(cur_set, 0, A, ans)
return ans
Implementing the same logic in C ++ results in a correct return value. However, when I do this in Python, all I get is a set of empty lists at the very end, and during iteration it copies the same current list to all the elements in the list, although the listing shows that it is every time adds the correct subset Why is this happening? Here is the result:
print subsets([1,2,3])
appending []
ans: [[]]
appending [3]
ans: [[3], [3]]
appending [2]
ans: [[2], [2], [2]]
appending [2, 3]
ans: [[2, 3], [2, 3], [2, 3], [2, 3]]
appending [1]
ans: [[1], [1], [1], [1], [1]]
appending [1, 3]
ans: [[1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3]]
appending [1, 2]
ans: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]
appending [1, 2, 3]
ans: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[], [], [], [], [], [], [], []]