首页  >  文章  >  web前端  >  JavaScript全排列的六种算法

JavaScript全排列的六种算法

高洛峰
高洛峰原创
2016-11-26 10:02:481636浏览

全排列是一种时间复杂度为:O(n!)的算法,前两天给学生讲课,无意间想到这个问题,回来总结了一下,可以由7种算法求解,其中动态循环类似回溯算法,实现起来比较繁琐,故总结了6种,以飨读者。所有算法均使用JavaScript编写,可直接运行。
算法一:交换(递归)
1.  
2.  
3.      
4.     Full Permutation(Recursive Swap) - Mengliao Software 
5.  
6.  
7. 

Full Permutation(Recursive Swap)
 
8. Mengliao Software Studio - Bosun Network Co., Ltd.
 
9. 2011.05.24

 
10.  
42.  
43. 
算法二:链接(递归)
1.  
2.  
3.      
4.     Full Permutation(Recursive Link) - Mengliao Software 
5.  
6.  
7. 

Full Permutation(Recursive Link)
 
8. Mengliao Software Studio - Bosun Network Co., Ltd.
 
9. 2012.03.29

 
10.  
33.  
34. 
算法三:回溯(递归)
1.  
2.  
3.      
4.     Full Permutation(Recursive Backtrack) - Mengliao Software 
5.  
6.  
7. 

Full Permutation(Recursive Backtrack)
 
8. Mengliao Software Studio - Bosun Network Co., Ltd.
 
9. 2012.03.29

 
10.  
59.  
60. 
算法四:回溯(非递归)
1.  
2.  
3.      
4.     Full Permutation(Non-recursive Backtrack) - Mengliao Software 
5.  
6.  
7. 

 
8. Full Permutation(Non-recursive Backtrack)
 
9. Mengliao Software Studio - Bosun Network Co., Ltd.
 
10. 2012.03.29

 
11.  
54.  
55. 
算法五:排序(非递归)
1.  
2.  
3.      
4.     Full Permutation(Non-recursive Sort) - Mengliao Software 
5.  
6.  
7. 

 
8. Full Permutation(Non-recursive Sort)
 
9. Mengliao Software Studio - Bosun Network Co., Ltd.
 
10. 2012.03.30

 
11.  
66.  
67. 
算法六:求模(非递归)
1.  
2.  
3.      
4.     Full Permutation(Non-recursive Modulo) - Mengliao Software 
5.  
6.  
7. 

Full Permutation(Non-recursive Modulo)
 
8. Mengliao Software Studio - Bosun Network Co., Ltd.
 
9. 2012.03.29

 
10.  
54.  
55. 
    上面的六种算法有些是对位置进行排列,例如回溯、排序等,因为这样可以适应各种类型的元素,而非要求待排列元素一定是数字或字母等。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn