Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
1, Elements in a subset must be in non-descending order.
2, 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], [] ]分析:
看见return all 首先想dfs能不能解决。
将num数组排序之后,相同元素就挨在一起,可以判断重复。
遍历数组,将每一个元素加入item,再递归得对后面的部分进行搜索。
public class Solution { public List<List<Integer>> subsetsWithDup(int[] num) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> item = new ArrayList<Integer>(); Arrays.sort(num); result.add(item);//empty set dfs(result, item, num, 0); return result; } private void dfs(List<List<Integer>> result, List<Integer> item, int[] num, int pos){ for(int i=pos; i<num.length; i++){ item.add(num[i]); result.add(new ArrayList<Integer>(item)); dfs(result, item, num, i+1); item.remove(item.size()-1); while(i<num.length-1 && num[i]==num[i+1]) i++;//ignore duplicate } } }