题目描述
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
样例
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
想法一:
创建一个内函数 通过遍历start到nums的长度 遍历递归调用函数 然后加入到res中
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
def temp(start, num):
res.append(num)
for i in range(start, len(nums)):
temp(i+1, num+[nums[i]])
temp(0, [])
return res
想法二:
参考了别人代码 这个思路很简单 就是依次遍历nums列表中的数字 双重循环 第二重遍历res列表中的元素 给每个元素中添加nums中的数字 下面举个例子 比如按照样例中[1,2,3]
初始化 [ [ ] ]
第一次大循环完 [ [ ], [1] ]
第二次大循环完 [ [ ], [1], [2], [1,2] ]
第三次大循环完 [ [ ], [1], [2], [3], [1,3], [1,2], [2,3], [1,2,3] ]
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = [[]]
for num in nums:
for temp in res[:]:
x = temp[:]
x.append(num)
res.append(x)
return res
最后
刷过的LeetCode源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063


442

被折叠的 条评论
为什么被折叠?



