1. 程式人生 > >Leetcode 90. Subsets II

Leetcode 90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Answer:

class Solution(object):
    def combinehelper(self,n,k,current,result):
        if k<=0:
            if result not in self.results:
                self.results.append(result)
            return
        if current>n or n-current+1<k:
            return
        tempresult=list(result)
        tempresult.append(self.nums[current-1])
        self.combinehelper(n,k-1,current+1,tempresult)
        tempresult=list(result)
        self.combinehelper(n,k,current+1,tempresult)
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        self.nums=sorted(nums)
        self.results=[]
        l=len(nums)
        for i in range(l+1):
            self.combinehelper(l,i,1,[])
        return self.results