A simple and pretty Python Solution with good Runtime


  • 0
    B

    I used a recursive approach to the problem. The problem gave a good opportunity to make use of generators and yield constructions. Hopefully, it can be useful to look at for people.

    from copy import deepcopy
    
    
    class Solution(object):
        def permuteUnique(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            count_dic = dict()
            for i in nums:
                count_dic[i] = count_dic.get(i,0) +1
            return permuteUnique_dic(count_dic)
    
    def permuteUnique_dic(dic):
    
        if len(dic) == 0:
            return [[]]
    
        item = dic.popitem()
        to_be_inserted = item[0]
        list1 = permuteUnique_dic(dic)
        full_list = []
        for p in insertionPlaces(len(list1[0]), item[1]):
            new_list = deepcopy(list1)
            for insertion_point in p:
                for li in new_list:
                    li.insert(insertion_point,to_be_inserted)
            full_list = full_list + new_list
        return full_list
    
    def insertionPlaces(max, count):
        """
        :param max: max of the range [Int]
        :param count: [The number of Places]
        :Yields all possible intger list in order
        """
        a = [0] * count
        flag = True
        while flag:
            yield a
            flag = False
            for i in range(count):
                if a[i] < max:
                    a[i] += 1
                    flag = True
                    for j in range(i):
                        a[j] = a[i]
                    break
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.