Simple Java Solution Using Bit Operations


  • 11
    A
    public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        int n = nums.length;
        List<List<Integer>> subsets = new ArrayList<>();
        for (int i = 0; i < Math.pow(2, n); i++)
        {
            List<Integer> subset = new ArrayList<>();
            for (int j = 0; j < n; j++)
            {
                if (((1 << j) & i) != 0)
                    subset.add(nums[j]);
            }
            Collections.sort(subset);
            subsets.add(subset);
        }
        return subsets;
    }
    

    }


  • 1
    F

    Great solution! The Math.pow(2, n) part can run faster by using 1 << n, too.


  • 0
    E

    but wouldnt this become very complicated if we have more than 32 elements in that set?


  • 0
    G

    I think it's not good to solve the problem like this unless interviewer tells you there are at most 32 elements in array


  • 0
    A

    you can use long instead of int which allow you at most 64 elements. I don't think a computer could compute all subsets if a set has more than 64 elements.


Log in to reply
 

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