我写了这段代码
def rec_offspring(n,offspring):
if n == 1:
return [[sprng] for sprng in offspring]
else:
return [[sprng1] for sprng1 in offspring] +\
[sprng2 for sprng2 in rec_offspring(n-1,offspring)]
如何更改它以便返回uniqes列表?
例如:
rec_offspring(3,[1,2,3])
应该返回:
[[2,3,1],[3,2,1],[1,3,2],[3,1,2],[1,2,3],[2,1,3]
答案 0 :(得分:0)
如果你想要一个递归函数,你可以使用回溯来创建排列:
def permute(a, i, out=None):
if out is None:
out = []
if i == len(a):
out.append(a)
else:
for j in range(i, len(a)):
a[i], a[j] = a[j], a[i]
permute(a, i + 1,out)
a[i], a[j] = a[j], a[i]
return out
print(permute([1,2,3],0))
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]