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

你可能感兴趣的:(leetcode算法学习,深度优先,算法)