LeetCode 78 [Subsets]

原题

给定一个含不同整数的集合,返回其所有的子集

如果 S = [1,2,3],有如下的解:

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

子集中的元素排列必须是非降序的,解集必须不包含重复的子集

解题思路

  • Backtracking, DFS
  • 首先,数组要排序,在第n层,加入一个元素进入n+1层,删除刚刚加入的元素,加入第n层的第二个元素......
                                   [ ]
                                /   |   \
                             [1]   [2]   [3]
                           /  |     |
                    [1, 2] [1, 3] [2, 3]
                      /
                [1, 2, 3]

完整代码

# 方法一
class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if nums is None:
            return []
        res = [[]]
        self.dfs(sorted(nums), 0, [], res)
        return res

    def dfs(self, nums, index, path, res):
        for i in xrange(index, len(nums)):
            res.append(path + [nums[i]])
            path.append(nums[i])
            self.dfs(nums, i+1, path, res)
            path.pop()

# 方法二
class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if nums is None:
            return []
        res = [[]]
        self.dfs(sorted(nums), 0, [], res)
        return res

    def dfs(self, nums, index, path, res):
        for i in xrange(index, len(nums)):
            res.append(path + [nums[i]])
            self.dfs(nums, i+1, path+[nums[i]], res)

# 方法三
class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        result = [[]]
        for x in nums:
            with_x = []
            for s in result:
                with_x.append(s + [x])
            result = result + with_x
    return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,002评论 0 33
  • Given a set of distinct integers, nums, return all possib...
    ShutLove阅读 222评论 0 0
  • Given a set of distinct integers, nums, return all possib...
    关玮琳linSir阅读 386评论 0 1
  • 1、用C语言实现一个revert函数,它的功能是将输入的字符串在原串上倒序后返回。 2、用C语言实现函数void ...
    希崽家的小哲阅读 6,753评论 0 12
  • 徘徊于空寂的花海 嗅着花香 一丝丝愁绪萦绕在心头 何时走完漫漫长路 走香斑驳的记忆 忧思深沉如海 虽漫步在花海 却...
    鹿晗的迷妹阅读 345评论 0 3

友情链接更多精彩内容