Premiumlab  

https://leetcode.com/problems/subsets/#/description

 

 

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

 

 

Sol 1:

 

Iteration.

 

Next element is based on the previous ones + the current number.

 

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        # iteratively 
        res = [[]]
        for num in nums:
            res += [item + [num] for item in res]
        return res

 

 

Sol 2:

 

DFS. Recursion. 

 

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        # DFS recursively
        res = []
        self.dfs(sorted(nums), 0, [], res)
        return res
    
    def dfs(self, nums, index, path, res):
        # path adds up to result 
        res.append(path)
        # Call dfs recursively on the rest of/ unvisited list 
        for i in range(index, len(nums)):
            self.dfs(nums, i+1, path + [nums[i]], res)

 

 

posted on 2017-07-08 11:37  Premiumlab  阅读(124)  评论(0编辑  收藏  举报