C++中全排列函数next_permutation 用法

 

全排列参考了两位的博客 感谢!

http://blog.sina.com.cn/s/blog_9f7ea4390101101u.html

http://blog.csdn.net/ac_gibson/article/details/45308645

早就听说了了next_permutation 产生全排列的强大,一直到昨晚遇到一个对字符串产生全排列的问题才知道这个函数的强大,我们队是按照dfs去搞全排列,然后在进行字符串的匹配,结果写的很长,过程中还各种debug。。。于是决定今天学一下...

 

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

 

我们来看下面这个例子:

 

[cpp]  view plain  copy
 
  1. #include <iostream>  
  2. #include <algorithm>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     int num[3]={1,2,3};  
  7.     do  
  8.     {  
  9.         cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;  
  10.     }while(next_permutation(num,num+3));  
  11.     return 0;  
  12. }  

 

 

 

 

 

输出结果为:

当我们把while(next_permutation(num,num+3))中的3改为2时,输出就变为了:

由此可以看出,next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列,同时并改变num数组的值。

另外,需要强调的是,next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。比如,如果数组num初始化为2,3,1,那么输出就变为了:

 

此外,next_permutation(node,node+n,cmp)可以对结构体num按照自定义的排序方式cmp进行排序。

也可以对字符...

next_permutation 自定义比较函数 POJ 1256

题目中要求的字典序是

//'A'<'a'<'B'<'b'<...<'Z'<'z'.

。。。
 
 

#include<iostream> //poj 1256 Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b) 
{
 if(tolower(a)!=tolower(b))//tolower 是将大写字母转化为小写字母.
 return tolower(a)<tolower(b);
 else
 return a<b;
}
int main()
{
 char ch[20];
 int n;
cin>>n;
 while(n--)
{
scanf("%s",ch);
sort(ch,ch+strlen(ch),cmp);
 do
{
printf("%s\n",ch);
}while(next_permutation(ch,ch+strlen(ch),cmp));
}
 return 0;
}

 

 


练习

 

 

博主个人公众号开通啦,平时主要分享一些机器学习、深度学习等的论文和方法,以及算法与数据结构、大厂经验贴等!欢迎大家关注,一起交流进步!

在这里插入图片描述

 

 

  • 164
    点赞
  • 415
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值