说我有一个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: (from https://en.wikipedia.org/wiki/Permutation#/media/File:Permutations_RGB.svg - https://commons.wikimedia.org/wiki/File:Permutations_RGB.svg)
更多推荐
发布评论