Given an integer array nums that may contain duplicates, return all possible subsets (the power set) without duplicate subsets, in any order.
Sort, then backtrack as in Subsets. At each depth, only the first of several equal values may be chosen; picking a later copy would build the same subsets again.
1function subsetsWithDup(nums: number[]): number[][] {2nums.sort((a, b) => a - b);3const res: number[][] = [], path: number[] = [];4function dfs(start: number) {5res.push([...path]);6for (let i = start; i < nums.length; i++) {7if (i > start && nums[i] === nums[i - 1]) continue;8path.push(nums[i]);9dfs(i + 1);10path.pop();11}12}13dfs(0);14return res;15}
Record [].
Space: play/pause · ←/→: step