LintCode 17 LeetCode 78 – Python 3 (Week 09 – 02)

Most all possible solution problem is about searching. Most searching questions can be solved by recursion.

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
    
        ans = []        
        self.dfs(nums, 0, [], ans)
        return ans
        
    def dfs(self, nums, index, path, ans):
        ans.append(path)
        for i in range(index, len(nums)):
            self.dfs(nums, i+1, path + [nums[i]], ans)

Time complexity is O(n * 2^n). Space complexity is 0(1).

Leave a comment

Design a site like this with WordPress.com
Get started