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
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.