Power Set with Bit Manipulation

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array nums of distinct integers, return all possible subsets (the power set) using bitwise operations.

Use bit manipulation to iterate through all possible inclusion/exclusion combinations. Each integer from 0 to 2^n - 1 represents a unique subset, where each bit indicates whether the corresponding element is included.

The solution set must not contain duplicate subsets. Return the subsets in any order.

Examples

Example 1:

Input: nums = [1,2,3]

Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Explanation: There are 2^3 = 8 subsets. Each number from 0 to 7 in binary maps to a subset: 000→[], 001→[1], 010→[2], 011→[1,2], 100→[3], 101→[1,3], 110→[2,3], 111→[1,2,3].

Example 2:

Input: nums = [0]

Output: [[],[0]]

Explanation: There are 2^1 = 2 subsets: the empty set and the set containing 0.

Example 3:

Input: nums = [1,2]

Output: [[],[1],[2],[1,2]]

Explanation: There are 2^2 = 4 subsets.

Constraints

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All elements of nums are unique.
Source: Subsets pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle