One line python solution´ with explanation


  • 0
    N

    Each number needs to 'decide' if he is part of the set or not, this is done using the corresponding bit of the number:

    1. Where n is the length of the array, there are 2 ** n options for the sets. These options can be represented as a binary number: If the bit is 1 we will insert the number to the set, otherwise we won't.
    2. We need to build a binary number that will have a bit for each number in the array, meaning each binary number will be in the length of n (For example - if nums is [5,60, 7] then we can't generate '1' and '01', we need to generate '001' and '010')
    class Solution(object):
        def subsets(self, nums):
            return [[nums[j] for j in xrange(len(nums)) if bin(i)[2:].zfill(len(nums))[j] == '1'] for i in xrange(2 ** len(nums))]
    
    

Log in to reply
 

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