上级排列:prev_permutation(start, end) //求的是当前排列的上一个排列
下级排列:next_permutation(start, end) //求的是当前排列的下一个排列
对于“上一个”和“下一个”,它们为字典序的前后,就是对于当前序列Pn,他的下一个序列Pn+1,不存在另外的Pm,使得Pn<Pm<Pn+1。
字典序:不同排列的先后关系是从左——>右逐个比较对应的数字的先后来决定的。
例如:——对于6个数字的排列123456和123465,按照字典序的定义,123456排在123465的前面。
——比较单词(lead和leader),把短的排前面。
对于next_permutation函数,其原型为:
#include<algorithm>
bool next_permutation(iterator start, iterator end)
当当前序列不存在下一个排列时,返回false,否则返回true。
对于这两个函数一般和do ~ while搭配。
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int num[3] = {1, 2, 3};
do{
printf("%d %d %d\n", num[0], num[1], nu[2]);
}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
可以从中看出这个函数是对数组num中的前n个元素进行全排列,同时并改变num[ ]的值 。
如果把初始数组改为:int num = {2, 3, 1};则输出结果为:
2 3 1 3 1 2 3 2 1
可以从中看出这个结果是在初始值往后的全排列。
如果输入的是字符串,原代码改为:
char ch[50];
scanf("%s", ch);
int n = strlen(ch);
sort(ch, ch+strlen(ch));
do{
puts(ch);
}while(next_permutation(ch, ch+n));
样例:题目链接:https://www.51nod.com/Challenge/Problem.html#!#problemId=1384
代码实现:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
char s[12];
scanf("%s", s);
int l = strlen(s);
sort(s, s+l);
do{
puts(s);
}while(next_permutation(s, s+l));
return 0;
}
题目链接:http://poj.org/problem?id=1256
代码实现:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int val(char c)
{
// 按照'A'<'a'<...<'Z'<'z'的顺序,每个字母赋一个固定的权值
if(c>='A' && c<='Z')
return 2*(c-'A');
else
return 2*(c-'a')+1;
}
bool cmp(char a, char b)
{
return val(a) < val(b);
}
int main()
{
int T;
char str[20];
scanf("%d", &T);
while(T--)
{
cin >> str;
int n = strlen(str);
sort(str, str+n, cmp);
do{
cout << str << endl;
}while(next_permutation(str, str+n, cmp));
}
return 0;
}