debugging leetcode子集解决方案调试

dzjeubhm  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(121)

subsets ii
基本上,您必须打印所有唯一子集。例如,如果nums = [1,2,2],则res = [[], [1], [1, 2], [2], [2,2], [1,2,2]]
我的代码给出res = [[], [1], [1, 2], [2]]

def subsets_dfs(nums):
    nums.sort()
    res = []
    def dfs(nums, res, cur, pos):
        res.append(cur)
        for i in range(pos, len(nums)):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            dfs(nums, res, cur + [nums[i]], i + 1)
    dfs(nums, res, [], 0)
    return res
xurqigkl

xurqigkl1#

在中,如果i〉0且nums[i] == nums[i-1],则i〉0应为i〉pos

def subsets_dfs(nums):
    nums.sort()
    res = []
    def dfs(nums, res, cur, pos):
        res.append(cur)
        for i in range(pos, len(nums)):
            if i > pos and nums[i] == nums[i-1]:
                continue
            dfs(nums, res, cur + [nums[i]], i + 1)
    dfs(nums, res, [], 0)
    return res

相关问题