Description

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

  • Input: nums = [1,2,3]
  • Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

  • Input: nums = [0]
  • Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.

Submitted Code

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def backtrack(start):
            res.append(path[:])

            for i in range(start, len(nums)):
                path.append(nums[i])
                backtrack(i + 1)
                path.pop()

        res = []
        path = []
        backtrack(0)

        return res

Runtime: 1 ms | Beats 10.07%
Memory: 19.23 MB | Beats 92.59%

nums = [1,2,3]

path=[]

backtrack(0)
i=0 → path=[1]

  backtrack(1)
  i=1 → path=[1,2]
  
    backtrack(2)
    i=2 → path=[1,2,3]
    
      backtrack(3)

    pop → path=[1,2]
    
  pop → path=[1]

  i=2 → path=[1,3]
  
    backtrack(3)

  pop → path=[1]

pop → path=[]
----------------------
i=1 → path=[2]

  backtrack(2)
  i=2 → path=[2,3]

    backtrack(3)

  pop → path=[2]

pop → path=[]
----------------------
i=2 → path=[3]

  backtrack(3)

pop → path=[]

return [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]]

Other Solutions

1st

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = []
            nums.sort()
            for i in xrange(1<<len(nums)):    # 1 << 3 = 8
                tmp = []
                for j in xrange(len(nums)):
                    if i & 1 << j:            # if i >> j & 1:
                        tmp.append(nums[j])
                res.append(tmp)
            return res

time complexity: 𝑂(𝑛*2𝑛)
space complexity: 𝑂(𝑛*2𝑛)

bitmask를 사용해서 재귀 호출보다 훨씬 빠르게 푸는 방법도 있다.

nums = [1,2,3]

i  j   binary   subset
0      000      []
   0  &001=f
   1  &010=f
   2  &100=f
1      001      [1]
   0  &001=t  → nums[0]
   1  &010=f
   2  &100=f
2      010      [2]
   0  &001=f
   1  &010=t  → nums[1]
   2  &100=f
3      011      [1,2]
   0  &001=t  → nums[0]
   1  &010=t  → nums[1]
   2  &100=f
4      100      [3]
5      101      [1,3]
6      110      [2,3]
7      111      [1,2,3]

return [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]

Leave a comment