LeetCode--078--子集(python)

Given a set of no repeating element integer array nums, which returns an array of all possible subsets (power set).

Description: Solution Set can not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
[3],
  [1],
  [2],
  [2,3],
  [1,3],
  [2,3],
  [1,2 ],
  []
]

 

Ideas: retrospective, nested in a recursive loop, recursive nature have a characteristic cycle

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

Two for, so that each subset of res already add the current form a new subset of 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

 

Guess you like

Origin www.cnblogs.com/NPC-assange/p/11457754.html