首页 > 解决方案 > 给定 n 和特定排列 s,按元素 1-n 的字典顺序找到下一个排列(python)

问题描述

例如,假设我们有NextInOrder(10,(1,2,4,7)),然后将这两个作为函数的输入,我希望编写一个 python 函数,该函数(1,2,4,8)通过按字典顺序查找下一个排列来返回,其中排列的元素在范围内1-10

所以另一个例子NextInOrder(10, (5,3,2,10))会返回(5,3,4,1)

标签: pythonpermutationlexicographiclexicographic-ordering

解决方案


您可以使用从最后一个位置开始的数字计数器方法。将最后一个位置增加到一个不在先前位置中的值。当下一个值超出范围时回溯到上一个位置。

例如:

def nextPerm(N,P):
    result = list(P)           # mutable permutation
    i = len(P)-1               # position to advance (start with last)
    while i in range(len(P)):  # advance/backtrack loop
        result[i] += 1         # next value at position
        if result[i] > N:      # value beyond range
            result[i]=0
            i -= 1             # backtrack
        elif result[i] not in result[:i]: # distinct values only
            i += 1             # next position to advance
    return None if i<0 else tuple(result)

输出:

P = (1,2,4,7)
while P:
    P = nextPerm(10,P)
    print(P)

(1, 2, 4, 8)
(1, 2, 4, 9)
(1, 2, 4, 10)
(1, 2, 5, 3)
(1, 2, 5, 4)
(1, 2, 5, 6)
(1, 2, 5, 7)
(1, 2, 5, 8)
(1, 2, 5, 9)
(1, 2, 5, 10)
(1, 2, 6, 3)
...

推荐阅读