Tutorialspoint
Problem
Solution
Submissions

All Possible Subsets

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to generate all possible subsets of a set of distinct integers. The solution should return the subsets in any order.

Example 1
  • Input: nums[] = {1, 2, 3}
  • Output: {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}
  • Explanation:
    • Step 1: For the set {1, 2, 3}, we generate all possible subsets.
    • Step 2: The empty set {} is always a subset.
    • Step 3: Single element subsets: {1}, {2}, {3}
    • Step 4: Two element subsets: {1, 2}, {1, 3}, {2, 3}
    • Step 5: Three element subset: {1, 2, 3}
    • Step 6: Therefore, there are 2^3 = 8 possible subsets.
Example 2
  • Input: nums[] = {0}
  • Output: {{}, {0}}
  • Explanation:
    • Step 1: For the set {0}, we generate all possible subsets.
    • Step 2: The empty set {} is always a subset.
    • Step 3: The only other subset is {0} itself.
    • Step 4: Therefore, there are 2^1 = 2 possible subsets.
Constraints
  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All numbers in the input array are unique
  • Time Complexity: O(2^n * n), where n is the length of the input array
  • Space Complexity: O(2^n * n) for storing all subsets
SetControl StructuresSnowflakeTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • For a set of size n, there are 2^n possible subsets.
  • Each element in the set can either be included or excluded in a subset.
  • Use a bit manipulation approach where each bit position corresponds to an element's inclusion/exclusion.
  • Alternatively, use a backtracking approach to build subsets incrementally.
  • The power set property states that a set with n elements has 2^n subsets.

Steps to solve by this approach:

 Step 1: Calculate the total number of possible subsets, which is 2^n for n elements.

 Step 2: Use bit manipulation to represent each subset, where each bit indicates whether an element is included (1) or excluded (0).
 Step 3: For each number from 0 to 2^n-1, generate a subset based on its binary representation.
 Step 4: For each bit position that is 1, include the corresponding element from the original array in the current subset.
 Step 5: Allocate memory for each subset according to the number of elements it contains.
 Step 6: Fill each subset with the appropriate elements from the original array.
 Step 7: Return all generated subsets along with their sizes.

Submitted Code :