Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
与Subsets问题的唯一区别在于,一个满足条件的set加入到最终结果sets里面的时候,需要先检查sets里面是否已经存在这个set,如果重复,则不添加。
这还是一道列举所有case的NP的题,用recursion, 用arraylist
第二遍做法:需要已访问数组,当前后元素一样且前面元素并未访问,这个时候就是重复的case, continue,
注意这里的判重复条件跟3Sum那种是不一样的,这里是recursion, 3Sum不是
1 public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { 2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 3 ArrayList<Integer> item = new ArrayList<Integer>(); 4 if (num==null || num.length==0) return res; 5 Arrays.sort(num); 6 boolean[] visited = new boolean[num.length]; 7 for (int len=0; len<=num.length; len++) { 8 helper(res, item, num, 0, len, visited); 9 } 10 return res; 11 } 12 13 public void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> item, int[] num, int starter, int len, boolean[] visited) { 14 if (item.size() == len) { 15 res.add(new ArrayList<Integer>(item)); 16 return; 17 } 18 for (int i=starter; i<num.length; i++) { 19 if (i>0 && num[i]==num[i-1] && !visited[i-1]) continue; 20 item.add(num[i]); 21 visited[i] = true; 22 helper(res, item, num, i+1, len, visited); 23 item.remove(item.size()-1); 24 visited[i] = false; 25 } 26 }
第一遍做法:依赖arrraylist.contains()函数来查重,这样做其实不是很好,组合一多,时间代价挺高的
1 import java.util.*; 2 3 public class Solution { 4 public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { 5 java.util.Arrays.sort(num); 6 ArrayList<Integer> set = new ArrayList<Integer>(); 7 ArrayList<ArrayList<Integer>> sets = new ArrayList<ArrayList<Integer>>(); 8 9 for (int i = 0; i <= num.length; i++) { 10 helper(set, sets, num, i, 0); 11 } 12 return sets; 13 } 14 15 public void helper(ArrayList<Integer> set, ArrayList<ArrayList<Integer>> sets, int[] num, int i, int start) { 16 if (set.size() == i) { 17 if (!sets.contains(set)) { 18 sets.add(new ArrayList<Integer>(set)); 19 } 20 return; 21 } 22 for (int k = start; k < num.length; k++) { 23 set.add(num[k]); 24 helper(set, sets, num, i, k+1); 25 set.remove(set.size() - 1); 26 } 27 } 28 }