从 Python 和 C 中的列表中查找一个换位排列

Tec*_*ice 2 c python list

我有输入 A = [ 2,3,4,1]

输出只是 A 中元素的所有可能排列,这可以通过单次转置(两个相邻元素的单次翻转)操作来完成。所以输出是:

[3,2,4,1],[ 2,4,3,1],[2,3,1,4],[1,3,4,2]
Run Code Online (Sandbox Code Playgroud)

如何在 Python 中做到这一点?和/或C ?

编辑 允许循环换位。因此[2,3,4,1]==>[1,3,4,2]是允许的并且是有效的输出。

Tan*_*lam 5

A = [2,3,4,1]

res = []
for i in range(len(A)):
    temp = A[:]
    temp[i], temp[i-1] = temp[i-1], temp[i]
    res.append(temp)

print res
Run Code Online (Sandbox Code Playgroud)

结果:

[[1, 3, 4, 2], [3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4]]
Run Code Online (Sandbox Code Playgroud)