AlgoMaster Logo

Subsets

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Backtracking Approach

The backtracking technique is one of the simplest and intuitive ways to solve this problem. The main idea is to generate all possible subsets incrementally. Here's the detailed procedure:

  1. Recursion is used to explore inclusion or exclusion of each element in the subset being formed.
  2. Maintain a current subset list (path) and we include/exclude elements from nums.
  3. On reaching a point where no more elements are left to consider, record the current subset as a valid solution.
  4. Start with an empty subset [] and traverse all possible options.

Code:

2. Iterative Approach

The iterative approach builds the subsets directly using the concepts of combinatorial logic, by iteratively adding each element to existing subsets. Here's the thought process:

  1. Start with an empty subset.
  2. For each number in the array, iterate over all subsets formed so far and include the current number into them to form new subsets.
  3. Merge the newly formed subsets into the result.

Code:

3. Bit Manipulation Approach

This approach uses the concept that each subset can be represented as a binary string of length n, where 1 indicates inclusion and 0 indicates exclusion.

  1. There are a total of 2^n subsets possible.
  2. Each subset corresponds to the binary representation of numbers from 0 to 2^n - 1.
  3. Convert the numbers into binary form, and include elements in the subset based on digit '1' positioning.

Code: