Leetcode 78. Subsets

https://leetcode.com/problems/subsets/

Medium

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

 1 class Solution:
 2     # Backtracking
 3     def subsets(self, nums: List[int]) -> List[List[int]]:
 4         if not nums:
 5             return None
 6         
 7         n_nums = len(nums)
 8         results = []
 9         
10         def helper(index, path):
11             results.append(path)
12             
13             for i in range(index, n_nums):
14                 helper( i + 1, path + [ nums[ i ] ] )
15         
16         helper(0, [])
17         
18         return results        
19 
20     # Iterative
21     def subsets2(self, nums: List[int]) -> List[List[int]]:
22         if not nums:
23             return None
24         
25         results = [ [] ]
26         
27         for num in nums:
28             results += [ item + [ num ] for item in results ]
29         
30         return results
31 
32     # Bit manipulation
33     def subsets3(self, nums: List[int]) -> List[List[int]]:
34         if not nums:
35             return None
36         
37         results = []
38         
39         # check each subset
40         for i in range( 1 << len( nums ) ):
41             current = []
42 
43             # check if nums[j] is in current subset
44             for j in range( len( nums) ):
45                 if (i >> j) & 1:
46                     current.append( nums[ j ] )
47 
48             results.append(current)
49         
50         return results
View Python Code

转载于:https://www.cnblogs.com/pegasus923/p/11343074.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值