Subsets

 

78. Subsets

Solution 1

  1. Each element can be contained or not contained.

  2. Consider these two situations and continuously append the prefix to the result.

def subsets(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    self.res = []
    def generate(sub_nums, is_contained):
        if len(sub_nums) == 1:
            if is_contained:
                return [sub_nums]
            else:
                return [[]]

        res = generate(sub_nums[1:], True)
        res.extend(generate(sub_nums[1:], False))
        if is_contained:
            prefix = [sub_nums[0]]
            res = map(lambda r: prefix + r, res)
        return res
    
    self.res = generate(nums, True)
    self.res.extend(generate(nums, False))
    return self.res

Solution 2

  1. For each result in the result list, append the num in nums or not.
def subsets(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    result = [[]]
    for num in nums:
        result += [i + [num] for i in result]
    return result