Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
public class Solution { public List<List> subsetsWithDup(int[] nums) { List<List> res = new ArrayList<List>(); if (nums == null || nums.length == 0) { return res; } List tem = new ArrayList(); Arrays.sort(nums); helper(res, tem, nums,0); return res; } public void helper(List<List> res, List tem, int[] nums, int index) { res.add(new ArrayList(tem)); if (index >= nums.length) { return; } for (int i = index; i < nums.length; i++) { //去重复:与i不同的是有重复的数字, 例如[1,2(1)] [1,2(2)]情况相同, 递归过程中每次新选取的可以是和递归数组相同的,(比如nums是[1,2,2,2] 当前递归栈是[1,2(1)] 新加入的[1,2(1), 2(2)]是合法的) 但是后面的元素就不能相同了([1, 2(1), 2(3)]就不合法 因为重复了)。 //新选取的元素在递归栈里就是每次当i取index得值时候, 所以当i!=index的值时候来去重 //因为i = index的时候,虽然122的第二个2,但是由于i = index也是可以加入的 if (i != index && nums[i] == nums[i - 1]) { continue; } tem.add(nums[i]); helper(res, tem, nums, i + 1); tem.remove(tem.size() - 1); } } }