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
nums
are 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
0
to2^n - 1
(wheren
is the size of the input set). - Each number
i
in this range represents a unique subset. The binary representation ofi
determines which elements are included in the subset.
Inner Loop: Deciding Which Elements to Include:
- For each
i
, a new vectorpath
is created to store the current subset. - The inner loop iterates through each bit of
i
. i >> j
shifts the bits ofi
right byj
places. This effectively checks each bit ofi
from right to left.- The
& 1
operation checks if the rightmost bit is1
. If it is, it means the element at indexj
innums
should be included in the current subset. - If the condition is true,
nums[j]
is added topath
.