EASY JAVA SOLUTION USING COMBINATORICS


  • 0
    A
    List<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        if(nums.length == 0){
            return null;
        }
        Arrays.sort(nums);
        int size = (int)Math.pow(2,nums.length);
        for(int i = 0; i < size; i++){
            result.add(convertToList(i,nums));
        }
        return result;
        
    }
    public List<Integer> convertToList(int x, int[] nums){
        List<Integer> subset = new ArrayList<>();
        int index = 0;
        for(int i = x; i > 0; i >>= 1){
            if((i&1)==1){
                subset.add(nums[index]);
            }
            index++;
        }
        return subset;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.