Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
给定一个数组,求它的所有有序子集。
思路:迭代法
遍历一次数组,每次将新的元素加入结果res中,并且作为下一步的拼接候选项。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
for n in nums:
res = self.helper(n,res)
if (len(nums) > 0):
res.append([])
return res
def helper(slef, n, res):
l = len(res)
for i in range(l):
item = res[i][:]
item.append(n)
res.append(item)
res.append([n])
return res
THE END.