Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
Java:
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> listinlist = new ArrayList<List<Integer>>();
if(nums.length <1) return listinlist;
Arrays.sort(nums);
List<Integer> newlist = new ArrayList<Integer>();
newlist.add(nums[0]);
listinlist.add(newlist);
for(int i=1; i<nums.length; i++)
{
generateList(listinlist, nums[i],nums[i-1]);
}
List<Integer> emptylist = new ArrayList<Integer>();
listinlist.add(0,emptylist);
return listinlist;
}
public void generateList(List<List<Integer>> listinlist, int m, int n)
{
int length = listinlist.size();
int start = (m==n)?length/2:0;
for(int i=start; i<length; i++)
{
List<Integer> list = listinlist.get(i);
List<Integer> newlist = new ArrayList<Integer>();
for(int j=0; j<list.size(); j++)
{
newlist.add(list.get(j));
}
newlist.add(m);
if(!listinlist.contains(newlist))
listinlist.add(newlist);
}
if(m!=n)
{
List<Integer> newlist = new ArrayList<Integer>();
newlist.add(m);
listinlist.add(newlist);
}
}
}
注意点:1.可以用Arrays.sort直接排序array
2. 可以直接listinlist.contains(newlist)查重
3.添加了int start = (m==n)?length/2:0; 可以省去一半的检查时间, 缺点是需要从1开始,以便可以传nums[i-1]的值