90. Subsets II

按照subset1的做法,回溯法,加了个排序和判断存不存在:

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) == 0:
            return []
        res = []
        temp = []
        self.hs(nums, temp, res, 0)
        return res
    def hs(self, nums, temp, res, i):
        if i == len(nums):
            temp.sort()
            if temp not in res:
                res.append(temp)
            return
        self.hs(nums, temp+[nums[i]],res, i+1)
        self.hs(nums, temp, res, i+1)

叠加法,加了回溯和判断存不存在:

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        if len(nums) == 0:
            return res
        res.append([])
        for n in nums:
            temp = []
            for t in res:
                m = t + [n]
                temp.append(m)
            res = res + temp
        temp = []
        for i in res:
            i.sort()
            if i not in temp:
                temp.append(i)
        return temp

你可能感兴趣的:(90. Subsets II)