个人学习用——STL之全排列

头文件

#include <algorithm> 

使用方法

  • next_permutation:求下一个排列组合

a.函数模板:next_permutation(arr, arr+size);
b.参数说明:
  arr: 数组名
  size:数组元素个数
c.函数功能: 返回值为bool类型,当当前序列不存在下一个排列时,函数返回false,否则返回true,排列好的数在数组中存储

d.注意:在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。
    比如,如果数组num初始化为2,3,1,那么输出就变为了:{2 3 1} {3 1 2} {3 2 1}

  • prev_permutation:求上一个排列组合

a.函数模板:prev_permutation(arr, arr+size);
b.参数说明:
  arr: 数组名
  size:数组元素个数
c.函数功能: 返回值为bool类型,当当前序列不存在上一个排列时,函数返回false,否则返回true
d.注意:在使用前需要对欲排列数组按降序排序,否则只能找出该序列之后的全排列数。

例题:请编写程序输出前n个正整数的全排列(n<10),并通过9个测试用例(即n从1到9)观察n逐步增大时程序的运行时间。
输入样例:

3

输出样例:

123
132
213
231
312
321

int main() {

	int n;
	cin>>n;
	int a[11];
	for (int i=0; i<n; i++)  
		a[i]=i+1;

	do {
		for (int i=0; i<n; i++)
			cout<<a[i];
		cout<<endl;
	} while (next_permutation(a,a+n));
	return 0;
}

转载自https://www.cnblogs.com/aiguona/p/7304945.html

猜你喜欢

转载自blog.csdn.net/qq_43640009/article/details/88585821