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,则该位所对应的数字在该结果集中。
- Python easy to understand solutions (DFS recursively, Bit Manipulation, Iteratively). - LeetCode Discuss
- C++ Recursive/Iterative/Bit-Manipulation - LeetCode Discuss
- My solution using bit manipulation - LeetCode Discuss
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