algorithm - 如何使用 Common Lisp 获取列表的所有可能排列?

标签 algorithm lisp common-lisp

我正在尝试编写一个 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/

相关文章:

python - Common Lisp——列表拆包? (类似于 Python)

unicode - MIT Scheme 在解释器中使用特殊字符

common-lisp - (defun (setf …)) defsetf 和 define-setf-expander 的典型用例是什么

java - 是否可以在事先不知道输入大小的情况下实现堆?

javascript - 查找最新更新json的有效算法

c++ - 检测 2 个长方体是否碰撞给出边界的算法

algorithm - 连通图中的 K-Clique

import - 用普通的 lisp 加载文件

lisp - CLISP 的 REPL 中有哪些魔法变量?

clojure - 有没有一种方法可以像 Clojure 中那样在 Common Lisp 中使用关键字作为函数?