[Lintcode]17. Subsets/[Leetcode]78. Subsets

17. Subsets/78. Subsets

  • 本题难度: Medium
  • Topic: Search & Recursion

Description

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

Example
Example 1:

Input: [0]
Output:
[
[],
[0]]
Example 2:

Input: [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]]
Challenge
Can you do it in both recursively and iteratively?

Notice
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.

我的代码

class Solution:
    """
    @param nums: A set of numbers
    @return: A list of lists
    """
    #no recursion

    def subsets(self, nums):
        # write your code here
        nums.sort()
        S = [[]]
        for num in nums:
            S = S + [i+[num] for i in S]
        return S

法2 recursion DFS

class Solution:
    """
    @param nums: A set of numbers
    @return: A list of lists
    """

    
    # recursion DFS
    def subsets(self, nums):
        # write your code here
        res = []
        nums.sort()
        self.dfs(nums,[],0,res)
        return res
        
    def dfs(self,nums,path,index,res):
        res.append(path)
        for i in range(index,len(nums)):
            self.dfs(nums,path+[nums[i]],i+1,res)

思路
[Lintcode]18. Subsets II/[Leetcode]90. Subsets II
一个简化版本,也不知道为什么放在后面。

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10386578.html
今日推荐