LC90. 子集 II

同层剪枝法

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        sol = []
        def backtrack(res, sol, begin):
            res.append(sol[:])
            for i in range(begin, len(nums)):
                if i > begin and nums[i-1] == nums[i]:
                    continue
                sol.append(nums[i])
                backtrack(res, sol ,i+1)
                sol.pop()
        backtrack(res, sol, 0)
        return res
used数组法
class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        sol = []
        vsd = [0]*len(nums)
        def backtrack(res, sol, vsd, begin):
            res.append(sol[:])
            for i in range(begin, len(nums)):
                if  i > 0 and nums[i] == nums[i-1] and vsd[i-1] == 0:
                    continue
                vsd[i] = 1
                sol.append(nums[i])
                backtrack(res, sol, vsd, i+1)
                vsd[i] = 0
                sol.pop()
        backtrack(res, sol, vsd, 0)
        return res  
上一篇:2021“MINIEYE杯”中国大学生算法设计超级联赛 第二场 题解


下一篇:Java基础05:运算符