Skip to content

Instantly share code, notes, and snippets.

@jingz8804 jingz8804/
Last active Aug 29, 2015

What would you like to do?
Subsets problem on LeetCode
import java.util.Arrays;
import java.util.ArrayList;
public class Subsets{
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
// sort the array first
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> emptySet = new ArrayList<Integer>();
// get the real subsets
results = subsets(results, S, 0);
return results;
private ArrayList<ArrayList<Integer>> subsets(ArrayList<ArrayList<Integer>> results, int[] S, int currentInd){
if (S == null) return results;
if (S.length == 1 || currentInd == S.length - 1){
ArrayList<Integer> set = new ArrayList<Integer>();
return results;
int temp = S[currentInd];
results = subsets(results, S, currentInd + 1);
// use this constructor instead. Better not to create an empty ArrayList and copy each element's clone to it.
ArrayList<ArrayList<Integer>> newSets = new ArrayList<ArrayList<Integer>>(results);
for(ArrayList<Integer> former: results){
ArrayList<Integer> present = new ArrayList<Integer>(former);
present.add(0, temp);
return newSets;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.