问题

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)
解集不能包含重复的子集。返回的解集中,子集可以按任意顺序排列

示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

示例 2:
输入:nums = [0]
输出:[[],[0]]

思路

用示例中的[1, 2, 2]来举例,如图所示:注意去重需要先对集合排序
leetcode-90:子集Ⅱ - 图1
从图中可以看出,同一树层上重复取2就要过滤掉,同一树枝上就可以重复取2,因为同一树枝上元素的集合才是唯一子集!

  1. class Solution {
  2. List<List<Integer>> result = new ArrayList<List<Integer>>();
  3. List<Integer> path = new ArrayList<>();
  4. public void backtracking(int[] nums, int startIndex, boolean[] used) {
  5. result.add(new ArrayList<>(path));
  6. for (int i = startIndex; i < nums.length; i++) {
  7. // used[i - 1] == true,说明同一树支candidates[i - 1]使用过
  8. // used[i - 1] == false,说明同一树层candidates[i - 1]使用过
  9. // 而我们要对同一树层使用过的元素进行跳过
  10. if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
  11. continue;
  12. }
  13. path.add(nums[i]);
  14. used[i] = true;
  15. backtracking(nums, i + 1, used);
  16. used[i] = false;
  17. path.remove(path.size() - 1);
  18. }
  19. }
  20. public List<List<Integer>> subsetsWithDup(int[] nums) {
  21. boolean[] used = new boolean[nums.length];
  22. Arrays.sort(nums);
  23. backtracking(nums, 0, used);
  24. return result;
  25. }
  26. }

List<List<Integer>> result = new ArrayList<List<Integer>>();可行 List<List<Integer>> result = new ArrayList<>();可行 List<List<Integer>> result = new ArrayList<List<>>();不可行