LeetCode OJ 系列之78 Subsets --Python

Problem:

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

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]
Answer:

class Solution(object):
    
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = self.subset_func(nums)
        for line in result:
            line.sort()
        return result
        
    def subset_func(self,nums):
        if len(nums)==0:
            return [[]]
        if len(nums)==1:
            return [[],nums]
        first = nums[0]
        tmp_nums = nums[1:]
        tmp_result = self.subset_func(tmp_nums)
        result = []
        for key in tmp_result:
            result.append(key)
            tmp = list(key)
            tmp.append(first)
            result.append(tmp)
        return result
        

Analysis:

利用动态规划的思想,当想要为集合A添加一个新的元素x时,得到的新集合A+1,必然是由下面两部分组成:

  • 集合A里所有的项
  • 集合A里每一项添加新的元素x之后形成的新项。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ln152315/article/details/49913797
文章标签: LeetCode Python OJ
个人分类: LeetCode Python
上一篇LeetCode OJ 系列之26 Remove Duplicates from Sorted Array --Python
下一篇LeetCode OJ 系列之217 Contains Duplicate --Python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭