Created
September 7, 2019 14:57
-
-
Save anil477/f75d15bfff8b8a2f22668421d4f84f42 to your computer and use it in GitHub Desktop.
Given a collection of integers that might contain duplicates, S, return all possible subsets.
This file contains 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
// https://www.interviewbit.com/problems/subsets-ii/ | |
import java.util.*; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
public class Solution { | |
public static void main(String[] args) { | |
Solution x = new Solution(); | |
ArrayList<Integer> l = new ArrayList<Integer>(); | |
l.add(1); | |
l.add(2); | |
l.add(2); | |
System.out.println(x.subsets(l)); | |
} | |
public Set<ArrayList<Integer>> subsets(ArrayList<Integer> a) { | |
Set<ArrayList<Integer>> output = new HashSet<ArrayList<Integer>>(); | |
output.add(new ArrayList<Integer>()); | |
if (a.size() == 0) { | |
return output; | |
} | |
Collections.sort(a); | |
generate(a, output, new ArrayList<Integer>(), 0); | |
return output; | |
} | |
public void generate(ArrayList<Integer> a, Set<ArrayList<Integer>> output, | |
ArrayList<Integer> temp, int index) { | |
for (int i = index; i < a.size(); i++) { | |
temp.add(a.get(i)); | |
output.add(new ArrayList<Integer>(temp)); | |
generate(a, output, temp, i + 1); | |
temp.remove(temp.size() - 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment