Subsets

The problem description can be found in LeetCode.

Approach

As usual, the space tree is our friend:

exampleroot*l1_11root--l1_1l1_xxroot--l1_xl2_2a2l1_1--l2_2al2_xaxl1_1--l2_xal2_2b2l1_x--l2_2bl2_xbxl1_x--l2_xbl3_3a3l2_2a--l3_3al3_xaxl2_2a--l3_xal3_3b3l2_xa--l3_3bl3_xbxl2_xa--l3_xbl3_3c3l2_2b--l3_3cl3_xcxl2_2b--l3_xcl3_3d3l2_xb--l3_3dl3_xdxl2_xb--l3_xd

At each step, we can either include the current element or exclude it (the x node). Lastly, it will be enough to append each solution we find in each leaf node to build up the expected result.

Solution

from typing import List class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: def dfs(i: int, curr: List[int], subs: List[List[int]]) -> None: if i == len(nums): subs.append(curr.copy()) return # include current element curr.append(nums[i]) dfs(i + 1, curr, subs) curr.pop() # do not include current element dfs(i + 1, curr, subs) ans: List[List[int]] = [] dfs(0, [], ans) return ans

Complexity

  • Time:
  • Space:

Where is the size of the nums list.