全排列函数next_permutation 用法
原文:链接
函数原型:
#include <algorithm> bool next_permutation(iterator start,iterator end)
返回值:
当 当前序列不存在下一个排列时,函数返回false,否则返回true
执行操作:
next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列,同时并改变num数组的值。
例子:
代码:
#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; }
输出结果为:
分类
next_permutation(start,end)
求的是当前排列的下一个排列
(字典序)
prev_permutation(start,end)
求的是当前排列的上一个排列
(字典序)
注意
在使用前需要对欲排列数组按升序排序,
否则只能找出该序列之后的全排列数。
可以对结构体num/字符串 按照自定义的排序方式cmp 进行排序。
next_permutation(node,node+n,cmp)
自定义比较函数举例
题目中要求的字典序是
'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; }
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/15187020.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步