我的问题是:给定长度n的列表L,和一个整数i,使得0℃= I&其中; ñ!你怎么能写一个函数烫发(L,N)生产的L在O(n)时间的第i个排列?我的意思第i个置换仅仅是第i个置换在一些实现定义排序是必须具备的特性:
有关的任何我的任何2列出了A和B,烫发(A,i)和烫发(B,I)都必须映射为一个相同的位置A和B的第j个元素的元素和B
对于任何输入(A,I),(A,J)烫发(A,I)==烫发(A,J),当且仅当我==学家
请注意:这不是功课。事实上,我2年前解决了这一点,但我已经完全忘记如何,它的杀了我。此外,这里是一个破碎的我尝试做一个解决方案:
高清烫发(S,I):
N = LEN(S)
烫发= [0] * N
itCount = 0
对于ELEM在S:
烫发[I%N + itCount] = ELEM
I = I / N
N - = 1
itCount + = 1
回报烫发
另外请注意:在O(n)的要求是非常重要的。否则,你可能只是产生N!所有排列的大名单,刚刚返回它的第i个元素。
解决方案 高清烫发(序列,索引):
序列=列表(序列)
结果= []
对于x中的xrange(LEN(序列)):
IDX =索引%LEN(序列)
指数/ = LEN(序列)
result.append(序列[IDX])
#恒定的时间不为了preserving拆除
序列〔IDX] =序列[-1]
德尔序列[-1]
返回结果
根据该算法洗牌,但是我们每次决定采取的,而不是一个随机数元素取数的至少显著一部分。可替代地考虑它像转换成一些任意碱不同的是基名称收缩为每个附加位的问题。
My question is: given a list L of length n, and an integer i such that 0 <= i < n!, how can you write a function perm(L, n) to produce the ith permutation of L in O(n) time? What I mean by ith permutation is just the ith permutation in some implementation defined ordering that must have the properties:
For any i and any 2 lists A and B, perm(A, i) and perm(B, i) must both map the jth element of A and B to an element in the same position for both A and B.
For any inputs (A, i), (A, j) perm(A, i)==perm(A, j) if and only if i==j.
NOTE: this is not homework. In fact, I solved this 2 years ago, but I've completely forgotten how, and it's killing me. Also, here is a broken attempt I made at a solution:
def perm(s, i):
n = len(s)
perm = [0]*n
itCount = 0
for elem in s:
perm[i%n + itCount] = elem
i = i / n
n -= 1
itCount+=1
return perm
ALSO NOTE: the O(n) requirement is very important. Otherwise you could just generate the n! sized list of all permutations and just return its ith element.
解决方案def perm(sequence, index):
sequence = list(sequence)
result = []
for x in xrange(len(sequence)):
idx = index % len(sequence)
index /= len(sequence)
result.append( sequence[idx] )
# constant time non-order preserving removal
sequence[idx] = sequence[-1]
del sequence[-1]
return result
Based on the algorithm for shuffling, but we take the least significant part of the number each time to decide which element to take instead of a random number. Alternatively consider it like the problem of converting to some arbitrary base except that the base name shrinks for each additional digit.