'Leetcode's Subsets problem solution not working I don't know why

**

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.

Example 1:

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

My solution -

let subsets = function(nums) {
    
let output = []

function backtrack(nums, subset = [], index = 0) {
    if(index === nums.length) {
        output.push(subset)
        return
    }
    // ith element is not considered
    backtrack(nums, subset, index + 1)
    
    // ith element is considered
    subset.push(nums[index])
    backtrack(nums, subset, index + 1)
    subset.pop()
    
    
}

    backtrack(nums)
    return output

};
console.log(subsets([1,2,3]))


Output:

[
  [], 
  [], 
  [], 
  [],
  [], 
  [], 
  [], 
  [],
]

Expected Output: 
[
  [],
  [1],
  [2],
  [3],
  [1,2],
  [1,3],
  [2,3],
  [1,2,3]
]

I don't know why the output array is empty while I am pushing the subset in it in the backtrack function.



Solution 1:[1]

The problem is here:

if(index === nums.length) {
        output.push(subset)
        return
    }

When you push the subset, you are passing reference. When you finish running the code, each subset in output array is referencing []. That is why you are returning array of []'s. Instead, you should copy the values and then push it.

output.push([...subset])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yilmaz