Problems178
Search for a command to run...
Sort the input
The plain power set would emit duplicate subsets whenever the input repeats a value. Sorting, then jumping past every copy on the reject branch, keeps each distinct subset appearing exactly once.
Sort + Skip Duplicates
1function func(ind, arr, nums, ans) {2 if (ind === nums.length) { ans.push([...arr]); return; }3 4 // Take nums[ind]5 arr.push(nums[ind]);6 func(ind + 1, arr, nums, ans);7 arr.pop();8 9 // Reject it — and skip every duplicate of it10 for (let j = ind + 1; j < nums.length; j++) {11 if (nums[j] !== nums[ind]) {12 func(j, arr, nums, ans);13 return;14 }15 }16 17 // Nothing distinct left18 func(nums.length, arr, nums, ans);19}20 21function subsetsWithDup(nums) {22 const ans = [], arr = [];23 nums.sort((a, b) => a - b);//nums: [1,2,2]24 func(0, arr, nums, ans);25 return ans;26}