Friday, August 26, 2016

LeetCode Print all subsets of a set

Reference:
https://leetcode.com/problems/subsets/

Solution References:
http://bangbingsyb.blogspot.com/2014/11/leetcode-subsets-i-ii.html
Above solution has clear implementations in  C++

Solution in Java
package subsets;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

public class Solution {
public static void main (String args[])
{
Solution s1 = new Solution();
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);a.add(2);a.add(3);
System.out.println(s1.subsets(a));
}
public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> a
{
  //we sort the list in order to be the output in lexicographically sorted order
Collections.sort(a);
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
res.add(new ArrayList<Integer>());
combination(a,res,temp,0);
return res;
   
}
static void combination(ArrayList<Integer> a,ArrayList<ArrayList<Integer>>res,ArrayList<Integer> temp,int index)
{
for(int i = index;i<a.size();++i)
{
temp.add(a.get(i));
//we make deep copy of temp list since java by default will do a shallow copy hence it will remove elements from result list .
res.add(new ArrayList(temp));
combination(a, res, temp,i+1);
temp.remove(temp.size()-1);
}
}
}

No comments:

Post a Comment