【回溯法DFS】78. 子集1、90. 子集 II

目录

78. 子集1

leetcode: 问题详情.

b站: 视频详解.

方法一、回溯法

class Solution(object):
    def subsets(self, nums):

        def backtracking(start_index, nums, path, res):
            res.append(copy.deepcopy(path))  # 让[]也加入res
            for i in range(start_index, len(nums)):
                path.append(nums[i])
                backtracking(i+1, nums, path, res)
                path.pop()
                
        if not nums:
            return []
        res = []
        path = []
        start_index = 0
        backtracking(start_index, nums, path, res)
        return res

90. 子集 II

leetcode: 问题详情.

b站: 视频详解.

方法一、回溯法+剪枝

class Solution(object):
    def subsetsWithDup(self, nums):

        def backtracking(start_index, res, path):
            res.append(copy.deepcopy(path))
            for i in range(start_index, len(nums)):
                if i>start_index and nums[i] == nums[i-1]:  # 剪枝
                    continue
                path.append(nums[i])
                backtracking(i+1, res, path)
                path.pop()
            
        start_index = 0
        res = []
        path = []
        nums.sort()
        backtracking(start_index, res, path)
        return res

上一篇:2021-2-25 62. 不同路径(动态规划)


下一篇:1.大数据概述