一尘不染

给定词典索引的数字置换算法

algorithm

我正在寻找一种算法,该算法给定一组数字(例如1 2 3)和索引(例如2),这将使我根据词典顺序对这些数字进行第二次置换。例如,在这种情况下,算法将返回1 3
2。


阅读 201

收藏
2020-07-28

共1个答案

一尘不染

这是一个简单的解决方案:

from math import factorial # python math library

i = 5               # i is the lexicographic index (counting starts from 0)
n = 3               # n is the length of the permutation
p = range(1, n + 1) # p is a list from 1 to n

for k in range(1, n + 1): # k goes from 1 to n
    f = factorial(n - k)  # compute factorial once per iteration
    d = i // f            # use integer division (like division + floor)
    print(p[d]),          # print permuted number with trailing space
    p.remove(p[d])        # delete p[d] from p
    i = i % f             # reduce i to its remainder

输出:

3 2 1

时间复杂度是 ø (N ^ 2)如果p是一个列表,并且 ø (n)的摊销如果p是一个哈希表和factorial被预先计算。

2020-07-28