[LeetCode]78. 子集
2018-11-12 本文已影响3人
杏仁小核桃
78. 子集
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解法1
class Solution:
def subsets(self, nums):
res = []
nums.sort()
for i in range(0, len(nums)+1):
self.findSub(i, res, nums, [])
return res
def findSub(self, k, res_list, nums, sub_list):
if k == len(sub_list):
res_list.append(sub_list)
else:
for i in nums:
self.findSub(k, res_list, nums[nums.index(i)+1:], sub_list+[i])
解法2
解法1的简化版
class Solution:
def subsets(self, nums):
ans = []
def find(cur,num):
for i in range(len(num)):
ans.append(cur+[num[i]])
find(cur+[num[i]], num[i+1::])
find([], nums)
return ans+[[]]
解法3
class Solution:
def subsets(self, nums):
res = [[]]
for num in nums :
for temp in res[:] :
x = temp[:]
x.append(num)
res.append(x)
return res
解法4
class Solution:
def subsets(self, nums):
n=len(nums)
if n==0:
return []
res=[]
for i in range(2**n):
s=i
newlist=[]
for j in range(n):
bitj=s%2
s=s//2
if bitj:
newlist.append(nums[j])
res.append(newlist)
return res