Leetcode78. Subset Python implementation

Time:2021-7-30
  • Title Requirements:

Leetcode78. Subset Python implementation

  • Idea:

    • Define a res to save the result set
    • Traverse the array, add the current value to all values in the res result set, and then append to the result set. After traversing the array, res appends a [[]], which is the result
  • Core code:
res = [[]]

for i in range(len(nums)):
    for subres in res[:]:
        res.append(subres+[nums[i]])
return res

Full code:

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = [[]]

        for i in range(len(nums)):
            for subres in res[:]:
                res.append(subres+[nums[i]])
        return res