↓Skip to main content
  1. LeetCode/

LeetCode 78: Subsets

·1 min· ·
LeetCode Medium Array Backtracking Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-26

  • Submissions: Wrong Answer ×3 → Accepted → Memory Limit Exceeded → Accepted ×3

Approach
#

Subsets come from taking or skipping each element (Backtracking Variation 1), 2^n in all. Iteratively, start from [[]] and for each number x copy every current subset with x appended. With backtracking, dfs(start, path) records path and then picks the next element from start on.

My Attempts
#

The first three used the wrong variable, c + [nums], appending the whole array instead of the current number: [5] returned [[], [[5]]]. Using num passed. Another approach on 2022-10-30 hit Memory Limit Exceeded.

Solution
#

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = [[]]
        for x in nums:
            res += [s + [x] for s in res]
        return res

Complexity
#

Time O(n · 2^n), space O(n · 2^n) (output).

Mistakes to Avoid
#

  • Append the current number x, not the whole nums.

Interview Explanation
#

Each element is taken or skipped, so starting from the empty set I copy every existing subset with each new number appended, giving 2^n subsets in O(n · 2^n).

Related

LeetCode 90: Subsets II
·2 mins
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 90 note: sort first; for a number equal to the previous one, extend only the subsets created in the previous step
LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts
LeetCode 47: Permutations II
·2 mins
LeetCode Medium Array Backtracking Sorting
LeetCode 47 note: sort first, and within a level skip a value equal to the previous one when the previous one is unused
LeetCode 39: Combination Sum
·2 mins
LeetCode Medium Array Backtracking
LeetCode 39 note: numbers may be reused, so the next level starts at i (not i + 1), which also avoids duplicates differing only in order
LeetCode 40: Combination Sum II
·2 mins
LeetCode Medium Array Backtracking
LeetCode 40 note: each number is used once and duplicates exist, so sort, start the next level at i + 1, and skip equal values within a level
LeetCode 46: Permutations
·2 mins
LeetCode Medium Array Backtracking
LeetCode 46 note: each level picks one unused number, marked in a used array, and records when the path is full