Very clear 5 liner beats 94%


  • 0
    C

    Here's a quite fast and clear solution. Generates all possible 2^size subsets.

    Similar implementations can be used to account for situations / questions that ask for unique ( as in non repetitive) subsets: using DP or a set of sets ( python does not allow set objects to be mutable so we'd have to use frozensets inside the set)

    class Solution(object): 
        
        def subsets(self, nums):
            tree = [[]]
            for i in nums:
                tree += [child + [i] for child in tree]
            return tree
    

    The tree variable contains only the children at the lowest level. However, we've constructed the tree such that every level contains the parent nodes as well.
    root-> left = root for all cases.

    e.g:
    A =[1,2,3]
    tree = [[]] # root is the empty set

    (for i in nums): ---------------- []
    i=1, children: ----- [] ---------------------- [1]
    i=2, children: -[] ------- [2] --------- [1] --------- [1,2]
    i=3, children: [] [3] --- [2] [2,3] --- [1] [1,3] --- [1,2] [1,2,3]


Log in to reply
 

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