题目描述:
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集。 示例: 输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
SOLUTION1:迭代法
比较常规的迭代法思路,循环nums数组,每次访问其中元素,将其转化为数组并加到result二维数组当中。
CODE:
class Solution:
def subsets(self,nums):
'''
nums:list[int]
return:list[list[int]]
'''
if len(nums) == 0:
return [[]]
result = [[]]
for i in nums:
result = result + [[i] + num for num in result]
return result
SOLUTION2:递归法
CODE:
class Solution:
def subsets(self,nums):
if len(nums) == 0:
return [[]]
result = []
def helper(i,tmp):
result.append(tmp)
for j in range(i,len(nums)):
helper(j+1,tmp+nums[j])
helper(0,[])
return result