Home > Enterprise >  Was trying to solve the Leetcode 78 Print Subsets problem. Why am i getting the output list as like
Was trying to solve the Leetcode 78 Print Subsets problem. Why am i getting the output list as like

Time:06-21

def addsubsets(nums,el,i,n):
    if i==n:                    
        output.append(el)
        return

    el.append(nums[i])
    addsubsets(nums,el,i 1,n)
    el.remove(nums[i])
    addsubsets(nums,el,i 1,n)
        
output=[]
                
nums=[1,2,3]
addsubsets(nums,[],0,len(nums))   
print(output)

#I was expecting output list as[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]. i am not able to understand why the output list is not getting appended with the list "el". Please help me to understand.!

Problem statement: Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

CodePudding user response:

Because you are adding a reference of the same list (el) to the output. And then removing elements from el.

Try output.append(el.copy())

  • Related