Subsets

也是一道传统回溯题,只需要注意每次DFS都需要将当前数组加入结果就好

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        tmp, res = [], []
        self.helper(0, len(nums), tmp, res, nums)
        return res

    def helper(self, start, end, tmp, res, nums):
        if start >= end:
            ref = tmp[:]
            res.append(ref)
            return 

        res.append(tmp[:])
        for i in xrange(start, end):
            tmp.append(nums[i])
            self.helper(i + 1, end, tmp, res, nums)
            tmp.pop()

Subsets II

这道题因为有重复元素的出现,需要用一个排序之后去重的技巧筛掉多余的子集

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        tmp, res = [], []
        self.helper(nums, 0, len(nums), tmp, res)
        return res

    def helper(self, nums, start, end, tmp, res):
        res.append(tmp[:])

        if start >= end:
            return 

        for i in xrange(start, end):
            if i > start and nums[i] == nums[i - 1]:
                continue
            tmp.append(nums[i])
            self.helper(nums, i + 1, end, tmp, res)
            tmp.pop()

results matching ""

    No results matching ""