Note:
 This is a backtracking problem.
 Much like
Combination II
, we need to sort nums
first and use used[]
to keep track of prev elements.
 We need to add
every node
, instead of just leaf node
.
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example
1 2
 Input: nums = [1,2,2] Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

var subsetsWithDup = function(nums) { let ans = [[]]; let path = []; let used = [...Array(nums.length).fill(false)]; nums.sort((a,b) => (ab)); backtracking(nums, 0, used); return ans; function backtracking(nums, startIndex, used) { for (let i = startIndex; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i1] && used[i1] == false) { continue; } else { path.push(nums[i]); ans.push([...path]) used[i] = true; backtracking(nums, i + 1, used); used[i] = false; path.pop(); } } } };
