UVA 10098 Generating Fast(next_permutation 全排列函数)
Generating permutation has always been an important problem in computer science. In this problem
you will have to generate the permutation of a given string in ascending order. Remember that your
algorithm must be efficient.
Input
The first line of the input contains an integer n, which indicates how many strings to follow. The next
n lines contain n strings. Strings will only contain alpha numerals and never contain any space. The
maximum length of the string is 10.
Output
For each input string print all the permutations possible in ascending order. Not that the strings should
be treated, as case sensitive strings and no permutation should be repeated. A blank line should follow
each output set.
Sample Input
3
ab
abc
bca
Sample Output
ab
ba
abc
acb
bac
bca
cab
cba
abc
acb
bac
bca
cab
cba
题目大意:
给个字符串,输出他的所有组合形式
解题思路
组合数学中经常用到排列,这里介绍一个计算序列全排列的函数: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
(上面的话引自大佬博客https://blog.csdn.net/howardemily/article/details/68064377)
注意使用的时候要先对数组进行升序排列,否则只能找到从当前字典序往后的排列。
do
{
cout<<a<<endl;
}while(next_permutation(a,a+len));//调用生成下一个排列的函数
这个地方用do,因为如果是 aaa的话 他应该输出一次aaa,但是如果是
while(next_permutation(a,a+len));//调用生成下一个排列的函数
{
cout<<a<<endl;
}
那就没法输出了
- AC代码:
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
bool cmp(char a1,char a2)
{
return a1<a2;
}
int main()
{
char a[11];
int n;
cin>>n;
while(n--)
{
cin>>a;
int len=strlen(a);
sort(a,a+len,cmp);
do
{
cout<<a<<endl;
}while(next_permutation(a,a+len));//调用生成下一个排列的函数
cout<<endl;
}
return 0;
}