LeetCode(力扣)90. 子集 IIPython

LeetCode90. 子集 II

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/subsets-ii/

LeetCode(力扣)90. 子集 IIPython_第1张图片

代码

class Solution:
    def subsetsWithDup(self, nums):
        result = []
        path = []
        used = [False] * len(nums)
        nums.sort()  # 去重需要排序
        self.backtracking(nums, 0, used, path, result)
        return result

    def backtracking(self, nums, startIndex, used, path, result):
        result.append(path[:])  # 收集子集
        for i in range(startIndex, len(nums)):
            if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
                continue
            path.append(nums[i])
            used[i] = True
            self.backtracking(nums, i + 1, used, path, result)
            used[i] = False
            path.pop()

你可能感兴趣的:(leetcode,算法,职场和发展,python)