0

I am trying to run below code for printing all possible subsets using backtracking. I am able to see the desired value during recursion when I do console.log on subset variable. However, on storing it in powerset variable, the returned value is an empty array [ [], [], [], [] ] instead of [ [] , [1], [2], [1,2] ]

let powerset = []
let subset = []

const subsets = nums => {
  backtrack(nums, 0)
  return powerset
}

const backtrack = (nums, start) => {
  powerset.push(subset)

  for (let i = start; i < nums.length; i++) {
    subset.push(nums[i])
    //console.log(subset)
    backtrack(nums, i + 1)
    subset.pop()
  }
}

console.log(subsets([1, 2]))
Andreas
  • 21,535
  • 7
  • 47
  • 56
kpratihast
  • 842
  • 1
  • 10
  • 23
  • _"The `pop()` method removes the last element from an array and returns that element. This method changes the length of the array."_ – Andreas Apr 18 '20 at 11:24
  • As you can see in the output of the snippet the content of `powerset` is 4 times a reference to the same array. – Andreas Apr 18 '20 at 11:27

0 Answers0