-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy path78_Subsets.py
More file actions
35 lines (29 loc) · 808 Bytes
/
78_Subsets.py
File metadata and controls
35 lines (29 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
subsets = []
n = len(nums)
nums.sort()
# We know there are totally 2^n subsets,
# becase every num may in or not in one subsets.
# So we check the jth(0<=j<n) bit for every ith(0=<i<2^n) subset.
# If jth bit is 1, then nums[j] in the subset.
sum_sets = 2 ** n
for i in range(sum_sets):
cur_set = []
for j in range(n):
power = 2 ** j
if i & power == power:
cur_set.append(nums[j])
subsets.append(cur_set)
return subsets
"""
[0]
[]
[1,2,3,4,7,8]
"""