permutations with unique values

前端 未结 19 1427
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:53

itertools.permutations generates where its elements are treated as unique based on their position, not on their value. So basically I want to avoid duplicates like this:

19条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:30

    This is my solution with 10 lines:

    class Solution(object):
        def permute_unique(self, nums):
            perms = [[]]
            for n in nums:
                new_perm = []
                for perm in perms:
                    for i in range(len(perm) + 1):
                        new_perm.append(perm[:i] + [n] + perm[i:])
                        # handle duplication
                        if i < len(perm) and perm[i] == n: break
                perms = new_perm
            return perms
    
    
    if __name__ == '__main__':
        s = Solution()
        print s.permute_unique([1, 1, 1])
        print s.permute_unique([1, 2, 1])
        print s.permute_unique([1, 2, 3])
    

    --- Result ----

    [[1, 1, 1]]
    [[1, 2, 1], [2, 1, 1], [1, 1, 2]]
    [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]]
    

提交回复
热议问题