以下是我对递归版本的尝试。如何使用堆栈迭代地实现解决方案?
def get_prems(lst):
prems = []
if len(lst) == 0:
return prems
if len(lst) == 1:
prems.append([lst[0]])
return prems
for n in lst:
lst_without_n = list(lst)
lst_without_n.remove(n)
for n_prem in get_prems(lst_without_n):
n_prem = [n] + n_prem
prems.append(n_prem)
return prems
答案 0 :(得分:0)
您的功能对我不起作用。这是我得到的:
my1st = [1, 2, 3]
get_prems(my1st)
[[1, 2, 3]]
我会改用itertools模块:
list(permutations(my1st))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]