☰ All problems

Subsets

A pizza shop wants its online menu to list every possible combination of extra toppings, from a plain pizza with none of them to one with all of them. Each topping is identified by a distinct integer code in nums.

Return all subsets of nums (its power set): every possible selection of toppings, including the empty selection and the full set. Each subset must appear exactly once. The subsets can come in any order, and so can the codes inside each subset.

Example 1
Input: nums = [5,-2,9]
Output: [[],[5],[-2],[5,-2],[9],[5,9],[-2,9],[5,-2,9]]

Explanation: Each of the three toppings is either on the pizza or not, which gives 2³ = 8 combinations.

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

Explanation: A plain pizza, each topping on its own, and both together.

Constraints

  • nums holds between 1 and 10 topping codes.
  • The codes are distinct integers from -10 to 10.

Follow-up: What changes if two toppings can share a code (duplicates in nums) and each distinct combination must still appear 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