permutations with unique values

前端 未结 19 1698
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  Happy的楠姐
    2020-11-22 02:26

    ans=[]
    def fn(a, size): 
        if (size == 1): 
            if a.copy() not in ans:
                ans.append(a.copy())
                return
    
        for i in range(size): 
            fn(a,size-1); 
            if size&1: 
                a[0], a[size-1] = a[size-1],a[0] 
            else: 
                a[i], a[size-1] = a[size-1],a[i]
    

    https://www.geeksforgeeks.org/heaps-algorithm-for-generating-permutations/

提交回复
热议问题