Original link: https://leetcode.com/problems/subsets/
Output length = C(0,n) + C(1,n) … + C(n,n)
We can do it recursively.
When the length of nums is larger than 2, we exclude one element using a for loop and then call subsets function and pass the list with the very element.
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
op = self.helper(nums)
op.append([])
return op
def helper(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) <= 1:
return [[i] for i in nums]
else:
op = []
nex = self.helper(nums[1:])
op.extend(nex)
op.append([nums[0]])
op.extend([nums[0]] + i for i in nex)
return op
Problems in solving this question:
-
The difference among list.append(), list.extend, and list += list
list.append(list1)
take list1 as one element and concat to the tail of the listlist.extend(list1)
concat two listslist += list1
seems to be same as extend method