Medium
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.
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
nums
are unique.To solve this task using Python with a Solution
class, you can follow these steps:
Solution
.subsets
that takes nums
as an input parameter.nums
.nums
.result
to store the subsets.generate
that takes start
(starting index), subset
(current subset), and result
(list of subsets) as parameters.start
is equal to the length of nums
, append a copy of subset
to result
and return.i
starting from start
, append nums[i]
to subset
, recursively call generate
with i + 1
, subset
, and result
, then backtrack by removing the last element from subset
.generate
with start + 1
, subset
, and result
to explore other possibilities.result
.generate
function initially with start = 0
, an empty list subset
, and the result
list.result
list containing all possible subsets.Here’s the implementation:
class Solution:
def subsets(self, nums):
def generate(start, subset, result):
if start == len(nums):
result.append(subset[:])
return
generate(start + 1, subset, result)
subset.append(nums[start])
generate(start + 1, subset, result)
subset.pop()
result = []
generate(0, [], result)
return result
# Example usage:
solution = Solution()
print(solution.subsets([1, 2, 3])) # Output: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
print(solution.subsets([0])) # Output: [[], [0]]
This solution generates all possible subsets using backtracking. It explores all possible combinations of elements in the array nums
, resulting in a time complexity of O(2^n), where n is the number of elements in nums
.
from itertools import combinations
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
for i in range(n + 1):
for subset in combinations(nums, i):
res.append(list(subset))
return res