Subsets⚓︎
Description⚓︎
Given an integer array nums of unique elements, return all possible subsets (the power set).
A subset of an array is a selection of elements (possibly none) of the array.
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
- Input:
nums = [1,2,3] - Output:
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
- Input:
nums = [0] - Output:
[[],[0]]
Constraints:
1 <= nums.length <= 10-10 <= nums[i] <= 10- All the numbers of
numsare unique.
Solution⚓︎
Recursive Solution⚓︎
- Time complexity: \(O(n\times 2^n)\);
- Space complexity: \(O(n)\).
Iterative Solution Using Binary Representation⚓︎
Explanation:
Outer Loop: Generating Each Subset:
- This loop iterates through all possible binary representations of numbers from
0to2^n - 1(wherenis the size of the input set). - Each number
iin this range represents a unique subset. The binary representation ofidetermines which elements are included in the subset.
Inner Loop: Deciding Which Elements to Include:
- For each
i, a new vectorpathis created to store the current subset. - The inner loop iterates through each bit of
i. i >> jshifts the bits ofiright byjplaces. This effectively checks each bit ofifrom right to left.- The
& 1operation checks if the rightmost bit is1. If it is, it means the element at indexjinnumsshould be included in the current subset. - If the condition is true,
nums[j]is added topath.