Skip to content

78. Subsets

题目

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
  • All the numbers of nums are unique.
Related Topics
  • 位运算
  • 数组
  • 回溯

  • 👍 2508
  • 👎 0
  • 思路

    本题需要遍历所有的子集,属于部分排列问题, 需要记录 start 指针后移的全排列问题

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def subsets(self, nums: List[int]) -> List[List[int]]:
            res = []
    
            def backtrack(start, path):
                res.append(path[:])
    
                for i in range(start, len(nums)):
                    path.append(nums[i])
                    backtrack(i + 1, path)
                    path.pop()
    
            backtrack(0, [])
            return res
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(2 k)
    • 空间复杂度 O(K)
      • k = lens(nums)