关于全排列 (递归&next_permutation函数)

原创不易,转载请说明出处https://blog.csdn.net/Adusts

一、STL中的next_permutation和prev_permutation算法。

1.next_permutation

#include  
#include  
using namespace std;  
int main()  {  
    int a[] = {1,2,3};  
    do {  
        cout << a[0] << " " << a[1] << " " << a[2] << endl;  
    } while (next_permutation(a,a+3));
return 0;  
}  

输出结果:

关于全排列 (递归&next_permutation函数)_第1张图片

2.prev_permutation.

#include  
#include  
using namespace std;  
int main()  {  
    int a[] = {3,2,1};  
    do {  
        cout << a[0] << " " << a[1] << " " << a[2] << endl;  
    } while (prev_permutation(a,a+3));//求上一个排列数,初始数组用逆序来调用可以输出全排列  
    return 0;  
} 

输出结果:

关于全排列 (递归&next_permutation函数)_第2张图片

注:next_permutation 排的是它的下一组数组元素, prev_permutation 排的是它的上一组数组元素

二、递归法输出全排列

假设总共有n个元素,其核心是:将每个元素放到余下n-1个元素组成的队列最前方,然后对剩余元素进行全排列,依次递归下去。

比如:1 2 3
首先将1放到最前方(跟第1个元素交换),然后排列余下的2 3,然后将1放回本来位置 
结果 1 2 3;1 3 2
  
其次将2放到最前方(跟第1个元素交换),然后排列余下的1 3,然后将2放回原处
结果 2 1 3; 2 3 1
..........
 

如果是4个元素,就将元素依次放到第一个元素的位置,后面的排序类似前面的3元素排序。


#include 
using namespace std;
void permutation(int array[], int begin, int end) {
	int i;
	if(begin == end) {
		for(i = 0; i <= end; ++i) {
			cout<

输出结果:

关于全排列 (递归&next_permutation函数)_第3张图片


你可能感兴趣的:(关于全排列 (递归&next_permutation函数))