HELLO WORLD--一起加油(🍺)!|

kingwzun

园龄:3年6个月粉丝:111关注:0

全排列函数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;
}

输出结果为:
image

分类

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 中国大陆许可协议进行许可。

posted @   kingwzun  阅读(407)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起