C++全排列函数

C++全排列函数

头文件

#include

具体内容

  1. 函数原型:bool next_permutation(iterator start, iterator end);
  2. 返回值:布尔型
  3. 函数本体:
    1. next_permutation(开始,结束),输出所有比当前排列大的排列,顺序是从小到大。
    2. prev_permutation(开始,结束),输出所有比当前排列小的排列,顺序是从大到小。
  4. 这两个函数的排列区间都是左闭右开,如 next_permutation(a,a+10) ,被全排列的区间为[0,10),即数组中下标为 0 1 2 3 4 5 6 7 8 9 的元素。

代码示例
示例 1

#include
using namespace std;
#include  //为了使用 next_permutation() 函数 
int main()
{
 	int a[4]={0,1,2,3};
 	while(next_permutation(a+1,a+4)) //全排列函数,对数组中下标为 1 ~ 3 的元素进行全排列 
 	{
  		for(int i=1;i<=3;i++)
   			cout<<a[i]<<" ";
  		cout<<endl;
 	}
 	return 0;
} 

输出结果1
C++全排列函数_第1张图片


示例 2

#include
using namespace std;
#include  //为了使用 next_permutation() 函数 
int main()
{
 	int a[4]={0,2,1,3};
 	while(next_permutation(a+1,a+4)) //全排列函数,对数组中下标为 1 ~ 3 的元素进行全排列 
 	{
  		for(int i=1;i<=3;i++)
   			cout<<a[i]<<" ";
  		cout<<endl;
 	}
 	return 0;
} 

输出结果 2
C++全排列函数_第2张图片


示例 3

#include
using namespace std;
#include  //为了使用 next_permutation() 函数 
int main()
{
 	int a[4]={3,2,1,0};
 	while(next_permutation(a+1,a+4)) //全排列函数,对数组中下标为 1 ~ 3 的元素进行全排列 
 	{
  		for(int i=1;i<=3;i++)
   			cout<<a[i]<<" "; //因为 2 1 0后面没有比其还大的排列了,所以没有输出 
  		cout<<endl;
 	}
 	return 0;
} 

输出结果 3
在这里插入图片描述


示例 4

#include
using namespace std;
#include  //为了使用 prev_permutation() 函数 
int main()
{
 	int a[4]={3,2,1,0};
 	while(prev_permutation(a+1,a+4)) //全排列函数,对数组中下标为 1 ~ 3 的元素进行全排列 
 	{
  		for(int i=1;i<=3;i++)
   			cout<<a[i]<<" "; 
  		cout<<endl;
 	}
 	return 0;
} 

输出结果 4
C++全排列函数_第3张图片


示例 5

#include
using namespace std;
#include  //为了使用 prev_permutation() 函数 
int main()
{
 	string s="cba";
 	while( prev_permutation( s.begin(),s.end() ) ) 
 	{
  		cout<<s<<endl; 
 	}
 	return 0;
} 

输出结果 5
C++全排列函数_第4张图片

谢谢大家耐心的看完,如果有错误,请大佬指出,如果觉得不错,如果您比较富裕,请支持一下吧,谢谢!

C++全排列函数_第5张图片C++全排列函数_第6张图片

你可能感兴趣的:(算法小技巧,算法,全排列函数,C++)