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

链接
90. 子集 II - 力扣(LeetCode) (leetcode-cn.com)
解法一:直接回溯中剪枝
1 class Solution { 2 List<List<Integer>> res = new ArrayList<>(); 3 Deque<Integer> path = new LinkedList<>(); 4 5 public List<List<Integer>> subsetsWithDup(int[] nums) { 6 if(nums.length == 0) return res; 7 Arrays.sort(nums); 8 BackTracking(nums, 0); 9 return res; 10 } 11 12 public void BackTracking(int[] nums, int index) { 13 res.add(new ArrayList<>(path)); 14 if(index >= nums.length) return; 15 for(int i = index; i < nums.length; i++) { 16 if(i > index && nums[i] == nums[i - 1]) { 17 continue; 18 } 19 path.add(nums[i]); 20 BackTracking(nums, i + 1); 21 path.removeLast(); 22 } 23 } 24 }
解法二:Set去重
1 class Solution { 2 // List<List<Integer>> res = new ArrayList<>(); 3 Set<List<Integer>> res = new HashSet<>(); 4 // Deuqe<Integer> path = new ArrayDeque<>(); //List<List> 可以与 Deque,但 Set<List> 得 和 List 5 List<Integer> path = new ArrayList<>(); 6 7 public List<List<Integer>> subsetsWithDup(int[] nums) { 8 if(nums.length == 0) { 9 return new ArrayList<>(); 10 } 11 Arrays.sort(nums); 12 dfs(nums,0); 13 // return res; //需要改变 14 return new ArrayList<>(res); 15 } 16 17 public void dfs(int[] nums,int u){ 18 if(nums.length == u) { 19 res.add(new ArrayList<>(path)); 20 return; 21 } 22 // path.addLast(nums[u]); 23 path.add(nums[u]); 24 dfs(nums, u+1); 25 26 // path.removeLast(); 27 path.remove(path.size() - 1); 28 // 还得 加上下面这个 29 dfs(nums,u + 1); 30 } 31 }
参考
carl

浙公网安备 33010602011771号