Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example, If nums = [1,2,3], a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
URL: https://leetcode.com/problems/subsets/
Solution1:
class Solution(object):
def subsets(self, S):
def dfs(depth, start, valuelist):
res.append(valuelist)
if depth == len(S): return
for i in range(start, len(S)):
dfs(depth+1, i+1, valuelist+[S[i]])
S.sort()
res = []
dfs(0, 0, [])
return res
Solution2:
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = 1 << len(nums)
result = []
for i in range(0, n):
subset = self.convert(i, nums)
result.append(subset)
return result
def convert(self, i, nums):
k = i
index = 0
res = []
while k > 0:
if (k & 1) == 1:
res.append(nums[index])
k >>= 1
index += 1
return res