Subsets II Leetcode
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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], [] ]
这道题和前面的差不多,却因为typo debug了好久。。。= = 需注意start和i哪个是哪个。
去重的过程和之前一样。
public class Solution { List<List<Integer>> result; List<Integer> current; public List<List<Integer>> subsetsWithDup(int[] nums) { result = new ArrayList<>(); current = new ArrayList<>(); if (nums == null) { return result; } Arrays.sort(nums); helper(nums, 0); return result; } public void helper(int[] nums, int start) { result.add(new ArrayList<>(current)); for (int i = start; i < nums.length; i++) { if (i > start && nums[i] == nums[i - 1]) { continue; } current.add(nums[i]); helper(nums, i + 1); current.remove(current.size() - 1); } } }
这道题还有非递归的方法,比dfs稍微快一些。就是对于每个值,往现有的子集里加,形成新的子集。如果这个数与前面的数一样的话,就只往上一个数新生成的子集里面加就可以了。
public class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> result = new ArrayList<>(); List<Integer> current = new ArrayList<>(); if (nums == null) { return result; } result.add(current); Arrays.sort(nums); int size = 0; int begin = 0; for (int i = 0; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i - 1]) { begin = size; } size = result.size(); for (int j = begin; j < size; j++) { List<Integer> l = new ArrayList<>(result.get(j)); l.add(nums[i]); result.add(l); } begin = 0; } return result; } }