如何在长度为 n 的列表中生成长度为 k 的循环移位的所有排列。这里的移位是循环的和正确的。请注意:
如果 K==1 ,则没有班次。因此,这些 0 班次没有排列。
如果 K==2 ,这相当于交换元素。因此所有 n! 可以产生排列。
例如。if list is [1 4 2],K=2 (因此从 0 到 NK,循环)
P1: [1,4,2] #Original list. No shift.
P2: [4,1,2] #Shift from 0 of [1,4,2]
P3: [4,2,1] #Shift from 1 of [4,1,2] as 0 gives P1
P4: [2,4,1] #Shift from 0 of [4,2,1]
P5: [2,1,4] #Shift from 1 of [1,4,2] as 0 of P4=P3
P6: [1,2,4] #Shift from 0 of [2,1,4]
如果 K==3,事情会变得有趣,因为一些排列被遗漏了。
例如。if list=[1,3,4,2],K=3 (因此从索引 0 到 4-3,循环)
P1 : [1,3,4,2] #Original list. No shift.
P2 : [4,1,3,2] #Shift from 0th of [1,3,4,2]
P3 : [3,4,1,2] #Shift from 0th of [4,1,3,2]
P4 : [3,2,4,1] #Shift from 1th of [3,4,1,2] as 0th gives P1
P5 : [4,3,2,1] #Shift from 0th of [3,2,4,1]
P6 : [2,4,3,1] #Shift from 0th of [4,3,2,1]
P7 : [2,1,4,3] #Shift from 1th of [2,4,3,1] as 0th gives P3
P8 : [4,2,1,3] #Shift from 0th of [2,1,4,3]
P9 : [1,4,2,3] #Shift from 0th of [4,2,1,3]
P10: [2,3,1,4] #Shift from 1th of [2,1,4,3] as 0 from P9=P7,1 from P9=P1,1 from P8=P5
P11: [1,2,3,4] #Shift from 0th of [2,3,1,4]
P12: [3,1,2,4] #Shift from 0th of [1,2,3,4]
#Now,all have been generated, as moving further will lead to previously found values.
请注意,这些排列是应有的 (24) 的一半 (12)。 为了实现这个算法,我目前正在使用回溯。这是我迄今为止尝试过的(在 Python 中)
def get_possible_cyclic(P,N,K,stored_perms): #P is the original list
from collections import deque
if P in stored_perms:
return #Backtracking to the previous
stored_perms.append(P)
for start in xrange(N-K+1):
"""
Shifts cannot wrap around. Eg. 1,2,3,4 ,K=3
Recur for (1,2,3),4 or 1,(2,3,4) where () denotes the cycle
"""
l0=P[:start] #Get all elements that are before cycle ranges
l1=deque(P[start:K+start]) #Get the elements we want in cycle
l1.rotate() #Form their cycle
l2=P[K+start:] #Get all elements after cycle ranges
l=l0+list(l1)+l2 #Form the required list
get_possible_cyclic(l,N,K,stored_perms)
for index,i in enumerate(stored_perms):
print i,index+1
get_possible_cyclic([1,3,4,2],4,3,[])
get_possible_cyclic([1,4,2],3,2,[])
这会产生输出
[1, 3, 4, 2] 1
[4, 1, 3, 2] 2
[3, 4, 1, 2] 3
[3, 2, 4, 1] 4
[4, 3, 2, 1] 5
[2, 4, 3, 1] 6
[2, 1, 4, 3] 7
[4, 2, 1, 3] 8
[1, 4, 2, 3] 9
[2, 3, 1, 4] 10
[1, 2, 3, 4] 11
[3, 1 ,2, 4] 12
[1, 4, 2] 1
[4, 1, 2] 2
[4, 2, 1] 3
[2, 4, 1] 4
[2, 1, 4] 5
[1, 2, 4] 6
这正是我想要的,但要慢得多,因为这里的递归深度超过了 N>7。我希望,我已经清楚地解释了自己。任何人,有任何优化?