package leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class demo_99 { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); int visited[]=new int[nums.length]; List<List<Integer>> list=new ArrayList<List<Integer>>(); //设置每次要找的子集的长度 for(int n=0;n<=nums.length;n++) { backtrack(list, new ArrayList<Integer>(), nums, n, visited,0); } System.out.println(list); return list; } //回溯法找子集 public void backtrack(List<List<Integer>> list,List<Integer> li,int nums[],int n,int visited[],int start) { if(li.size()==n) { list.add(new ArrayList<Integer>(li)); } else { for(int i=start;i<nums.length;i++) { if(visited[i]==1) {continue;} if(i>start&&nums[i]==nums[i-1]) {continue;} if(li.size()<n) { visited[i]=1; li.add(nums[i]); backtrack(list, li, nums, n, visited,i+1); } visited[i]=0; li.remove(li.size()-1); } } } public static void main(String[] args) { // TODO Auto-generated method stub demo_99 d99=new demo_99(); int[] nums= {1,2,2}; d99.subsetsWithDup(nums); } }