Subsets
Given a set ofdistinctintegers,nums, return all possible subsets.
Note:The solution set must not contain duplicate subsets.
For example,
Ifnums=[1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Solution
DFS visit each subset from start index to len(nums). Logic graph below
Why mistaken for so long?
- typo. Bad habit. Never copy paste code. If you want to, it probably means you need a helper function
- Bad habit. Need to keep the coding variable name consistent. Because don't change variable meaning in different functions
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
res = [[]]
for start in range(n):
self.dfsVisit(start + 1, nums, res, [nums[start]])
return res
def dfsVisit(self, start, nums, res, cur):
if start > len(nums):
return
res.append(cur[:])
for i in range(start, len(nums)):
self.dfsVisit(i + 1, nums, res, cur + [nums[i]])