I'm attempting to solve this leetcode problem: https://leetcode.com/problems/subsets/
Here's the code that works:
function subset(set) {
const result = [];
helper(set, 0, [], result);
return result;
}
function helper(set, i, slate, result) {
if(i === set.length) {
result.push([...slate]);
return result;
}
// exclude i
helper(set, i+1, slate, result);
// include i
slate.push(set[i]);
helper(set, i+1, slate, result);
slate.pop();
}
subset([1,2,3])
For this line here:
result.push([...slate]);
Why is it that when I changed it to result.push(slate)
or result.push(...slate)
, neither works even though slate
itself is an array?
For the case of result.push(slate)
: Is this because arrays are stored by reference in JavaScript, so when I do slate.pop();
here, it also pops out that item that is pushed into the result array?
However, I don't understand the other case (result.push(slate)
) since it seems that in this case the individual items are pushed in, and not the arrays containing each of those items. Why is that?