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
posted on 2019-08-12 22:32  浩然119  阅读(163)  评论(0编辑  收藏  举报