我想出了以下功能:
def permutations(elements, arr, index):
if len(elements) == index:
print arr
for i in xrange(index, len(elements)):
arr[index] = elements[i]
permutations(elements, arr, index+1)
permutations([1,2,3], [0,0,0], 0)
但是,它正在打印:
[1, 2, 3]
[1, 3, 3]
[2, 2, 3]
[2, 3, 3]
[3, 2, 3]
[3, 3, 3]
我的递归有什么问题?
最佳答案
好吧,我发现这是一个 Java 字符串递归排列算法,我将其翻译成 Python。我认为这是最好的解决方案:
def permutation(aux, ls):
if len(ls) == 0:
print(aux)
else:
for i in range(len(ls)):
permutation(aux + [ls[i]], ls[0:i] + ls[i+1:len(ls)])
permutation([], [1, 2, 3])
这是输出:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
关于python - 使用递归查找数组的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935755/