leetcode(90)子集 2
子集2
class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); int len = nums.length; List<List<Integer>> result = new ArrayList<List<Integer>>(); int[] index = new int[len]; index[0] = 1; for(int i=1;i<len;++i) { if(nums[i]==nums[i-1]) { index[i] = index[i-1]+1; }else { index[i] = 1; } } subsetsWithDup2(nums,len,result,index); return result; } public void subsetsWithDup2(int[] nums, int len, List<List<Integer>> result, int[] index) { if(len == 0) { List<Integer> element = new ArrayList<>(); result.add(element); }else { subsetsWithDup2(nums, len - index[len-1], result,index); int size = result.size(); for(int i=0;i<size;++i) { List<Integer> tempElement = result.get(i); for(int j=0;j<index[len-1];++j) { tempElement = (List)((ArrayList)tempElement).clone(); tempElement.add(nums[len-1]); result.add(tempElement); } } } } }