LeetCode--078--子集(python)

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
[3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

思路:回溯,在循环中嵌套递归,递归自然就有了循环的特性

Solution().subsets([1,2,3])              

[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
1 class Solution:
2     def subsets(self, nums: List[int]) -> List[List[int]]:
3         res = []
4         def recursive(start,num):
5             res.append(num)
6             for i in range(start,len(nums)):
7                 recursive(i+1,num+[nums[i]])
8         recursive(0,[])
9         return res

两层for,每次让res中已有的子集添加当前的num形成新的子集

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
1 class Solution:
2     def subsets(self, nums: List[int]) -> List[List[int]]:
3         res = [[]]
4         for num in nums:
5             for temp in res[:]:
6                 t = temp[:]
7                 t.append(num)
8                 res.append(t)
9         return res

猜你喜欢

转载自www.cnblogs.com/NPC-assange/p/11457754.html