生成列表的所有可能排列的算法?(Algorithm to generate all possible permutations of a list?)

编程入门 行业动态 更新时间:2024-10-22 19:43:21
生成列表的所有可能排列的算法?(Algorithm to generate all possible permutations of a list?)

说我有一个n个元素的列表,我知道有n个! 可能的方法来排序这些元素。 什么是生成此列​​表所有可能排序的算法? 例如,我有列表[a,b,c]。 该算法将返回[[a,b,c],[a,c,b,],[b,a,c],[b,c,a],[c,a,b],[c,b , 一个]]。

我正在阅读这里http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations

但维基百科从来没有擅长解释。 我不太了解它。

Say I have a list of n elements, I know there are n! possible ways to order these elements. What is an algorithm to generate all possible orderings of this list? Example, I have list [a, b, c]. The algorithm would return [[a, b, c], [a, c, b,], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].

I'm reading this here http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations

But Wikipedia has never been good at explaining. I don't understand much of it.

最满意答案

基本上,对于从左到右的每个项目,生成剩余项目的所有排列(并且每个项目都添加有当前元素)。 这可以递归地(或者如果你喜欢疼痛迭代地),直到达到最后一个项目,在那里只有一个可能的顺序。

所以使用列表[1,2,3,4]生成所有以1开头的排列,然后以2开始的所有排列,然后是3,然后是4。

这有效地将问题从发现四个项目的列表到三个项目的列表中的一个排除。 在减少到2然后1个项目列表后,将会找到它们。 显示使用3个彩色球的过程排列示例: 红色,绿色和蓝色的彩色球排列排列图像 (来自https://en.wikipedia.org/wiki/Permutation#/media/File:Permutations_RGB.svg - https://commons.wikimedia.org/wiki/File:Permutations_RGB.svg )

Basically, for each item from left to right, all the permutations of the remaining items are generated (and each one is added with the current elements). This can be done recursively (or iteratively if you like pain) until the last item is reached at which point there is only one possible order.

So with the list [1,2,3,4] all the permutations that start with 1 are generated, then all the permutations that start with 2, then 3 then 4.

This effectively reduces the problem from one of finding permutations of a list of four items to a list of three items. After reducing to 2 and then 1 item lists, all of them will be found. Example showing process permutations using 3 coloured balls: Red, green and blue coloured balls ordered permutations image (from https://en.wikipedia.org/wiki/Permutation#/media/File:Permutations_RGB.svg - https://commons.wikimedia.org/wiki/File:Permutations_RGB.svg)

更多推荐

本文发布于:2023-08-05 18:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1437415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   排列   列表   Algorithm   permutations

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!