【leetcode系列】【算法】【中等】子集 II

题目:

题目链接: https://leetcode-cn.com/problems/subsets-ii/

解题思路:

"所有可能" = 回溯 + 剪枝

需要考虑的是不能包含重复的子集,所以在遍历时,如果某个元素已经当做首字符遍历过了,则需要跳过相同元素,使用下一个不重复的元素继续进行回溯

代码实现:

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        def create_res(start, nums, res, path):
            if start > len(nums):
                return
            
            for index in range(start, len(nums)):
                if index > start and nums[index] == nums[index - 1]:
                    continue
                    
                path.append(nums[index])
                res.append(path[:])
                create_res(index + 1, nums, res, path)
                path.pop()
                
        nums.sort()
        res = [[]]
        create_res(0, nums, res, [])
        return res
发布了100 篇原创文章 · 获赞 4 · 访问量 1473

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105303426