next_permutation函数:
组合数学中经常用到排列,这里介绍一个计算序列全排列的函数:next_permutation(start,end),和prev_permutation(start,end)。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后,严格来讲,就是对于当前序列pn,他的下一个序列pn + 1满足:不存在另外的序列pm,使pn < pm < pn+1.
对于next_permutation函数,其函数原型为:
#include <algorithm>
bool next_permutation(iterator start,iterator end)
当当前序列不存在下一个排列时,函数返回false,否则返回true
我们来看下面这个例子:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int num[3]={1,2,3};
do{
cout << num[0] << " " << num[1] << " " << num[2] << endl;
}while(next_permutation(num,num+3));
return 0;
}
输出结果为:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
当我们把while(next_permutation(num,num+3))中的3改为2时,输出就变为了:
1 2 3
2 1 3
由此可以看出,next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列,同时并改变num数组的值。
另外,需要强调的是,next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。比如,如果数组num初始化为2,3,1,那么输出就变为了:
2 3 1
3 1 2
3 2 1
此外,next_permutation(node,node+n,cmp)可以对结构体num按照自定义的排序方式cmp进行排序。
一、概念
从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。如果这组数有n个,那么全排列数为n!个。
比如a,b,c的全排列一共有3!= 6 种 分别是{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a}。
二、常用操作
1.头文件
#include <algorithm>
2.使用方法
这里先说两个概念:“下一个排列组合”和“上一个排列组合”,对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比b c都小,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}没有下一个元素。
1)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}
2)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 arr[] = {3,2,1};
cout<<"用prev_permutation对3 2 1的全排列"<<endl;
do{
cout << arr[0] << ' ' << arr[1] << ' ' << arr[2]<<'\n';
}
while ( prev_permutation(arr,arr+3) );//获取上一个较大字典序排列,如果3改为2,只对前两个数全排列
int arr1[] = {1,2,3};
cout<<"用next_permutation对1 2 3的全排列"<<endl;
do {
cout << arr1[0] << ' ' << arr1[1] << ' ' << arr1[2] <<'\n';
}
while ( next_permutation(arr1,arr1+3) );//获取下一个较大字典序排列,如果3改为2,只对前两个数全排列
//注意数组顺序,必要时要对数组先进行排序
return 0;
}
四、全排列递归思路
我们可以将这个排列问题画成图形表示,即排列枚举树,比如下图为{1,2,3}的排列枚举树,此树和我们这里介绍的算法完全一致;
算法思路:
(1)n个元素的全排列=(n-1个元素的全排列)+(另一个元素作为前缀);
(2)出口:如果只有一个元素的全排列,则说明已经排完,则输出数组;
(3)不断将每个元素放作第一个元素,然后将这个元素作为前缀,并将其余元素继续全排列,等到出口,出口出去后还需要还原数组;
代码
我的博客 全排列问题
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
int use[15],num[15],n;
void dfs(int now){
if(now == n+1){
for(int i = 1;i <= n;++i)
printf("%5d",num[i]);
puts("");
return;
}
for(int i = 1;i <= n;++ i){
if(!use[i]){
num[now] = i;
use[i] = 1;
dfs(now+1);
use[i] = 0;
}
}
}
int main(){
scanf("%d",&n);
dfs(1);
return 0;
}