Subsets

Medium
backtracking

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.

This is a classic backtracking problem that demonstrates the fundamental pattern: at each element, we have two choices - include it in the current subset or exclude it. By exploring both paths and backtracking, we generate all possible combinations.

The key insight is that every subset can be represented by a binary decision for each element: in (1) or out (0). For n elements, we have 2^n possible subsets.

Example 1

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Explanation: For each element, we choose to include or exclude it, generating all 8 (2^3) possible subsets.

Example 2

Input: nums = [0]
Output: [[],[0]]
Explanation: Single element has two subsets: empty set and the element itself.

Constraints

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique
Show Hints (4)
Hint 1: Think about what decision you make at each element. What are the two options?
Hint 2: At each position, you can either include the current element or skip it.
Hint 3: After making a choice, what happens next? How do you undo the choice to explore alternatives?
Hint 4: The backtracking template: make a choice, explore recursively, undo the choice (backtrack).
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?