78. Subsets
Array, Backtracking ·Problem Statement
link: LeetCode.cn LeetCode
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:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Input: nums = [0]
Output: [[],[0]]
Solution Approach
The solution uses a recursive (backtracking) approach to explore all potential subsets.
Algorithm
- Start by adding the empty subset to the result.
- For each number in the array, recursively generate all possible subsets that include this number.
- Continue this process until you have explored all elements and paths in the array, thereby generating all subsets.
Implement
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
def helper(i, path):
res.append(path)
for j in range(i, n):
helper(j + 1,path + [nums[j]] )
helper(0, [])
return res