Generate permutations of JavaScript array

后端 未结 4 1411
失恋的感觉
失恋的感觉 2020-11-27 06:20

I have an array of n different elements in javascript, I know there are n! possible ways to order these elements. I want to know what\'s the most effective (fastest) algorit

4条回答
  •  心在旅途
    2020-11-27 06:43

    Using Heap's method (you can find it in this paper which your Wikipedia article links to), you can generate all permutations of N elements with runtime complexity in O(N!) and space complexity in O(N). This algorithm is based on swapping elements. AFAIK this is as fast as it gets, there is no faster method to calculate all permutations.

    For an implementation and examples, please have a look at my recent answer at the related question "permutations in javascript".

提交回复
热议问题