Created
October 12, 2013 21:02
-
-
Save charlespunk/6954892 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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], | |
[] | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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