我正在尝试编写一个 Common Lisp 函数,它将为我提供列表的所有可能排列,每个元素仅使用一次。例如,列表 '(1 2 3) 将给出输出 ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)).
我已经写过一些类似的作品,但它很笨拙,并不总是有效,我什至都没有真正理解它。我不是在要求代码,只是可能需要一些关于如何思考它的指导。我不太懂写算法。
谢谢, 杰森
最佳答案
作为一种基本方法,“所有排列”都遵循这种递归模式:
all permutations of a list L is: for each element E in L: that element prepended to all permutations of [ L with E removed ]
If we take as given that you have no duplicate elements in your list, the following should do:
(defun all-permutations (list)
(cond ((null list) nil)
((null (cdr list)) (list list))
(t (loop for element in list
append (mapcar (lambda (l) (cons element l))
(all-permutations (remove element list)))))))
关于algorithm - 如何使用 Common Lisp 获取列表的所有可能排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2087693/