题
面试题 08.04. 幂集
幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解题思路
算是一种动态规划 用到 以前所有状态数据 注意 Python 复制数组数据要用 .copy()
代码
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
num_now = {
}
ans = [[]]
for data in nums:
if data not in num_now:
num_now[data] = True
size = len(ans)
for i in range(size):
temp = ans[i].copy()
temp.append(data)
ans.append(temp)
return ans