Problems178
Search for a command to run...
Initialization
At each index branch twice — once excluding that element, once including it. When the index runs off the end, the choices made so far form one complete subset.
Take / Not-Take
1function backtrack(index, n, nums, current, ans) {2 // Base case: every element has been decided3 if (index === n) {4 ans.push([...current]);5 return;6 }7 8 // Exclude nums[index]9 backtrack(index + 1, n, nums, current, ans);10 11 // Include nums[index]12 current.push(nums[index]);13 backtrack(index + 1, n, nums, current, ans);14 15 // Undo, so the caller sees current unchanged16 current.pop();17}18 19function powerSet(nums) {20 const ans = [];21 const current = [];22 backtrack(0, nums.length, nums, current, ans);//n: 3ans: []23 return ans;24}