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], [] ]
Time: O(2^n)
Space: O(N)
class Solution: def subsets(self, nums: 'List[int]') -> 'List[List[int]]': res = [] if nums is None or len(nums) == 0: return res self.helper(nums, 0, [], res) return res def helper(self, nums, index, combination, combinations): combinations.append(list(combination)) for i in range(index, len(nums)): combination.append(nums[i]) self.helper(nums, i + 1, combination, combinations) combination.pop()
这里牵扯到一个copy问题,如果不加list,那么copy的就是combination的reference,因此list之后的改变都会导致之前加入值的改变,加上list()之后就是建立了一个当前combination的copy,之后无论list如何改变,就不变了
因为append进去的不是一个数,而是一个object(这里就是list)。之后这个object被改变了的话,之前append进去的那个list也会跟着变。比如append [1] 之后,把这个[1] 改成[2] 再append进去,得到的会是[ [2], [2] ] 而不是[ [1], [2] ]