Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created October 12, 2013 21:02
Show Gist options
  • Save charlespunk/6954892 to your computer and use it in GitHub Desktop.
Save charlespunk/6954892 to your computer and use it in GitHub Desktop.
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],
[]
]
public class Solution {
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
Arrays.sort(num);
ArrayList<ArrayList<Integer>> out = new ArrayList<ArrayList<Integer>>();
out.add(new ArrayList<Integer>());
for(int i = 0; i < num.length; i++){
ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> old: out){
ArrayList<Integer> now = new ArrayList<Integer>(old);
now.add(num[i]);
temp.add(now);
}
out.addAll(temp);
while(i < num.length - 1 && num[i] == num[i + 1]){
i++;
ArrayList<ArrayList<Integer>> tempDup = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> old: temp){
ArrayList<Integer> now = new ArrayList<Integer>(old);
now.add(num[i]);
tempDup.add(now);
}
out.addAll(tempDup);
temp = tempDup;
}
}
return out;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment