标签:
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
For example,
If S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
本题与上一题“Subsets”的思路相同,不过在选择元素的时候需要将同一位置重复重现的元素排除。见代码中标注的地方。
List<List<Integer>> lists = new ArrayList<List<Integer>>(); public List<List<Integer>> subsetsWithDup(int[] num) { fastnumortingHelp(num, 0, num.length-1); for(int i=1; i<=num.length; i++) { subsetsHelper(num, i, 0, new ArrayList<Integer>()); } lists.add(new ArrayList<Integer>()); return lists; } //快排代码 public void fastnumortingHelp(int[] num, int start, int over) { if(start >= over) return; int left = start; int right = over; int compare = start; while(left < right) { while(left < right && num[right] >= num[compare]) { right--; } int tmp = num[right]; num[right] = num[compare]; num[compare] = tmp; compare = right; while(left < right && num[left] <= num[compare]) { left++; } tmp = num[left]; num[left] = num[compare]; num[compare] = tmp; compare = left; } fastnumortingHelp(num, start, left-1); fastnumortingHelp(num, left+1, over); } //从数组num中,取得k个元素,这k个元素的下标都需>=start public void subsetsHelper(int[] num, int k, int start, List<Integer> list) { if(k == 1) { for(int i=start; i<num.length; i++) { //将同一位置相同的元素跳过 if(i>start && num[i] == num[i-1]) continue; list.add(new Integer(num[i])); lists.add(new ArrayList<Integer>(list)); list.remove(new Integer(num[i])); } } else { for(int i=start; i<=num.length-k; i++) { //将同一位置相同的元素跳过 if(i > start && num[i]==num[i-1]) continue; list.add(new Integer(num[i])); subsetsHelper(num, k-1, i+1, list); list.remove(new Integer(num[i])); } } }
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4296251.html