Subsets

Problem

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]]

Intuition

The task is to find all possible subsets (the power set) of a given array of unique elements. A subset is a set that contains only distinct elements and can be obtained by selecting elements from the original array. The solution involves using a depth-first search (DFS) approach to explore all possible combinations of elements in the array.

Approach

Initialize Result List:

Create an empty list res to store the resulting subsets.
DFS Function:

Implement a DFS function (dfs) that takes an index i as an argument.
The base case is when i is equal to or exceeds the length of the array nums. In this case, add a copy of the current subset to the result res.
In the recursive case, include the element at index i in the subset and call the DFS function with i + 1.
After the recursive call, remove the last element from the subset to backtrack, and call the DFS function with i + 1 without including the element.
Main Function:

Call the DFS function with an initial index of 0.
Return Result:

Return the final result res.

Complexity

  • Time complexity:

The time complexity is O(2^n), where n is the number of elements in the array nums. Each element has two possibilities: either include it in the subset or exclude it.

  • Space complexity:

The space complexity is O(n) due to the recursion stack. Additionally, the space required for the subset list contributes to the space complexity. The result res contains 2^n subsets, each with an average length of n/2, resulting in a space complexity of O(n * 2^n).

Code

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = []
        subset = []

        def dfs(i):
            if i >= len(nums):
                res.append(subset.copy())
                return 

            subset.append(nums[i])
            dfs(i + 1)

            subset.pop()
            dfs(i + 1)

        dfs(0)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值