☰ All problems

65. Subsets

Given an array nums of distinct integers, return every possible subset of it (its power set), including the empty subset and nums itself.

Each subset must appear exactly once. The subsets may be returned in any order, and the numbers inside a subset may be in any order too.

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

Explanation: Three elements give 2³ = 8 subsets.

Example 2
Input: nums = [0]
Output: [[],[0]]
Example 3
Input: nums = [4,-2]
Output: [[],[4],[-2],[4,-2]]

Constraints

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All values in nums are distinct

Follow-up: What changes if nums may contain duplicates and the answer must still list each distinct subset only once?

💡 Hint 1

Each element is either in a subset or not, so there are exactly 2^n subsets.

💡 Hint 2

Build the answer step by step: start with [[]], and for every number, add a copy of each existing subset with that number appended.

💡 Hint 3

Alternatively, backtrack: at index i decide to include nums[i] or skip it, and record the current path at every step.

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
function subsets(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc