Skip to content

Instantly share code, notes, and snippets.

@anil477
Created August 11, 2019 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/bf1e233878addbd815ee4aa3ea707d7d to your computer and use it in GitHub Desktop.
Save anil477/bf1e233878addbd815ee4aa3ea707d7d to your computer and use it in GitHub Desktop.
Given a set of distinct integers, S, return all possible subsets.
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<>();
l.add(1);
l.add(2);
l.add(3);
System.out.println(x.subsets(l));
}
public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> a) {
ArrayList<ArrayList<Integer>> output = new ArrayList<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, ArrayList<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);
}
}
}
@anil477
Copy link
Author

anil477 commented Sep 7, 2019

WhatsApp Image 2019-09-07 at 9 33 15 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment