[leetcode] 78. Subsets
题目
Given an integer array nums
of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
- All the numbers of
nums
are unique.
思路
找出一个序列的所有子序列。设一个序列nums的有n个元素,那么可以得到如下公式:subsets(nums(n))=subsets(nums(n-1))+[subnet+[nums[n]] for subnet in subnets(n-1)]
。如果此时有序列[1],它的所有子序列为[[], [1]]
,那么序列[1,2]的所有子序列则为[[], [1]]+[[]+[2], [1]+[2]]=[[], [1], [2], [1, 2]]
,以此类推。
代码
python版本:
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
return reduce(lambda res, num: res+[i+[num] for i in res], nums, [[]])
本文来自博客园,作者:frankming,转载请注明原文链接:https://www.cnblogs.com/frankming/p/16067036.html