我在这里提出一个用python实现的解决方案
import itertools as it
L = ['a','b','c','d']
B = it.combinations(L,2)
swaplist = [e for e in B]
print 'List of elements to permute:'
print swaplist
print
unique_necklaces = []
unique_necklaces.append(L)
for pair in swaplist:
necklace = list(L)
e1 = pair[0]
e2 = pair[1]
indexe1 = L.index(e1)
indexe2 = L.index(e2)
#swap
necklace[indexe1],necklace[indexe2] = necklace[indexe2], necklace[indexe1]
unique_necklaces.append(necklace)
for n in unique_necklaces:
# Commented code display the rotation of the elements in each necklace
print 'Necklaces'
print n#, [n[-r:]+n[:-r]for r in (1,2,3)]
这个想法是通过两种元素的排列来构建不同的项链。对于四个元素 a、b、c、d 的列表,算法产生:
['a', 'b', 'c', 'd']
['b', 'a', 'c', 'd']
['c', 'b', 'a', 'd']
['d', 'b', 'c', 'a']
['a', 'c', 'b', 'd']
['a', 'd', 'c', 'b']
['a', 'b', 'd', 'c']