[LeetCode] 78. Subsets tag: backtracking

本文详细介绍了如何通过深度优先搜索(DFS)的回溯方法来生成一个整数集合的所有可能子集(幂集)。该算法确保了结果中不包含重复的子集,并且考虑到了特殊情况。文中提供了两种实现方式:一种使用了深拷贝,另一种则避免了深拷贝的使用。

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
 
这个题目思路就是类似于DFS的backtracking.
 
1. Constraints
1) No duplicate subsets and neither integers in the nums.
2) edge case len(nums) == 0 => [ [ ] ]  但是还是可以
 
2. Ideas
DFS 的backtracking    T: O(2^n)     S; O(n)
 
3. Code 
 
1) using deepcopy, but the idea is obvious, use DFS [] -> [1] -> [1, 2] -> [1, 2, 3] then pop the last one, then keep trying until the end. 
import copy
class Solution:
    def subsets(self, nums: 'List [int]') -> 'List [ List [int] ]' :
        ans = []
        def helper(nums, ans, temp, pos):
            ans.append(copy.deepcopy(temp))
            for i in range(pos, len(nums)):
                temp.append()
                helper(nums, ans, temp, i + 1)
                temp.pop()
        
        helper(nums, ans, [], 0)
        return ans

 

2) Use the same idea , but get rid of deepcopy
 
class Solution:
    def subsets(self, nums: 'List[int]') -> 'List[List[int]]':
        ans = []
        def helper(nums, ans, temp, pos):
            ans.append(temp)
            for i in range(pos, len(nums)):
                helper(nums, ans, temp + [nums[i]], i + 1)
        helper(nums, ans, [], 0)
        return ans

 


 
 
 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9440473.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值