-
-
Save anil477/bf1e233878addbd815ee4aa3ea707d7d to your computer and use it in GitHub Desktop.
Given a set of distinct integers, 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
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); | |
} | |
} | |
} |
Author
anil477
commented
Sep 7, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment