1

This is a classic backtracking problem , i dont know why we need to copy arr element inside recursive function in order for it to work correctly. If i dont copy. It will return blank array

def subsets(self, nums: List[int]) -> List[List[int]]:
        res = list()
        temp = list()
        def dfs(nums,i):
            if i==len(nums):
                res.append(temp.copy())
                return
            temp.append(nums[i])
            dfs(nums,i+1)
            temp.pop()
            dfs(nums,i+1)
        dfs(nums,0)
        return res
ms1241721
  • 11
  • 2
  • Those are lists, not arrays... – Mad Physicist Jul 07 '22 at 21:08
  • Does this answer your question? [Python: List of Objects changes when the object that was input in the append() function changes](https://stackoverflow.com/questions/24345712/python-list-of-objects-changes-when-the-object-that-was-input-in-the-append-f) – SomeDude Jul 07 '22 at 21:10

1 Answers1

2

the reason is that, when you append nums to results, nums can still be changed even if it's inside results. Therefore the elements inside results will be changed everytime you change the original nums (in fact in the result all the values are identical). If you create a copy for each element you put in results, instead, the elements will all have different values.