Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Explanation: All 2^3 = 8 subsets of [1,2,3] are listed.
Output: [[],[0]]
Explanation: Two subsets exist: the empty set and [0].
We use a classic backtracking approach where for each element we make a binary choice: either include it in the current subset or skip it. We maintain a running list and add it to the result at every recursive call (not just at leaves).
- Start with an empty current subset and call the recursive helper with index 0.
- At each call, add a copy of the current subset to the result list.
- Iterate from the current index to the end of the array, add
nums[i], recurse withi+1, then remove the last element (backtrack). - Because we always advance the start index, no element is reused and no subset is generated twice.
Complexity Analysis:
Time complexity: O(n * 2^n) — there are 2^n subsets and copying each takes O(n) in the worst case.
Space complexity: O(n) recursion stack depth, plus O(n * 2^n) for the output.