C++ STL 全排列函数使用例子 - N个数的全排列
一、问题描述
n个数字的全排列数为n!个。比如1,2,3的全排列一共有3!= 6 种,分别是{1, 2, 3}、{1, 3, 2}、{2, 1, 3}、{2, 3, 1}、{3, 1, 2}、{3, 2, 1}。
二、C++ STL 中排列算法的说明
相关函数包含在algorithm库中。主要有两个:next_permutation,prev_permutation。
-
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.注意:在使用前需要对欲排列数组按降序排序,否则只能找出该序列之后的全排列数。
三、使用例子
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
int d[100];
for (int i = 0; i < 100; i++)
d[i] = i+1;
cin >> n;
do
{
for (int i = 0; i < n; i++)
cout << d[i] << " ";
cout<<endl;
}while(next_permutation(d, d + n));
return 0;
}
输入:3
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1