全排列算法(next_permutation)

STL提供了两个用来计算排列组合关系的算法,分别是next_permutation和prev_permutation。前者是求出下一个排列组合,而后者是求出上一个排列组合。

举个例子:对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。

next_permutation的函数原型:

template<class BidirectionalIterator>  
bool next_permutation(  
      BidirectionalIterator _First,   
      BidirectionalIterator _Last  
);  
template<class BidirectionalIterator, class BinaryPredicate>  
bool next_permutation(  
      BidirectionalIterator _First,   
      BidirectionalIterator _Last,  
      BinaryPredicate _Comp  
 );  

算法思想:

在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。

然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调。

最后将第ii个元素之后(包括ii)的所有元素颠倒排序。

例如{0,1,2,3,4}全排列的实现:

全排列算法(next_permutation)

题目:

输出序列{1,2,3,4}字典序的全排列。

代码:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int array[4]={1,2,3,4};
	sort(array,array+4);    // 这个sort可以不用,因为{1,2,3,4}已经排好序
	while(next_permutation(array,array+4))
	{
		for(int i=0;i<4;++i)
			cout<<array[i]<<" ";
		cout<<endl;
	}
	return 0;
}