给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
LeetCode:https://leetcode-cn.com/problems/subsets-ii
public class Main { public static void main(String[] args) { System.out.println(subsetsWithDup(new int[]{1,2,2})); } public static List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); List<List<Integer>> out = new ArrayList<>(); List<Integer> local = new ArrayList<>(); help(out,local,nums,0); return out; } private static void help(List<List<Integer>> out, List<Integer> local, int[] nums, int i) { out.add(new ArrayList<>(local)); for (int j = i; j < nums.length; j++) { if (j==i || nums[j]!=nums[j-1]){ local.add(nums[j]); } else{ continue;//关键代码! } help(out,local,nums,j+1); local.remove(local.size()-1); } } }
输出: