题:https://leetcode.com/problems/subsets/description/
题目
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],
[]
]
思路
一般思路用递归,但原来写过一道类似的题目。
正因为可以用递归做,所以答案是有子答案产生的。本题中,答案=子答案 + 加新字符的子答案
code
import copy
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
reslist = [[]]
for i, num in enumerate(nums):
relist1 = []
for j, ele in enumerate(copy.deepcopy(reslist)):
ele.append(nums[i])
relist1.append(ele)
print()
reslist = reslist + relist1
return reslist