Subset

lc 78

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

time complexity n 2^n. space complexity 2^n

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums == null || nums.length == 0 ) return result;
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(nums);
        helper(result, list, nums, 0);
        return result;
    }

    public void helper(List<List<Integer>> result, List<Integer> list, int[] nums, int position){
        result.add(new ArrayList<Integer>(list));
        //if(position == nums.length) return;
        for(int i = position; i < nums.length; i++){
            list.add(nums[i]);
            helper(result, list, nums, i + 1);
            list.remove(list.size() - 1);

        }
    }
}

bit method

private static final double LOG_2 = Math.log(2);

public static List<List<Integer>> sebsuet(List<Integer> inputSet){
  List<List<Integer>> res = new Arraylist<>();
 for(int i = 0; i < (1 <<inputSet.size()); i++){
   int bit = i;
   List<Integer> list = new Arraylist<Integer>();
   while( bit != 0){
     list.add(inputSet.get((int)(Math.log(bit & ~(bit - 1))/ LOG_2)));
     bit &= bit - 1;
   }
   res.add(list);

 }
return res;
}

results matching ""

    No results matching ""