转载:
1.http://blog.csdn.net/hackbuteer1/article/details/6657435
2.http://blog.sina.com.cn/s/blog_9f7ea4390101101u.html
3.http://www.slyar.com/blog/stl_next_permutation.html
4.http://www.cplusplus.com/reference/algorithm/next_permutation/
5.原理介绍:点击打开链接
1.)
#include "iostream"
#include "algorithm"
using namespace std;
void permutation(char* str,int length)
{
sort(str,str+length);
do
{
for(int i=0;i<length;i++)
cout<<str[i];
cout<<endl;
}while(next_permutation(str,str+length));
}
int main(void)
{
char str[] = "acb";
cout<<str<<"所有全排列的结果为:"<<endl;
permutation(str,3);
system("pause");
return 0;
}
2).
、有一定约束条件的全排列
对数1,2,3,4,5要实现全排序。要求4必须在3的左边,其它的数位置随意。
思路:首先实现全排列,然后对全排列进行筛选,筛选出4在3左边的排列。
#include "iostream"
#include "algorithm"
using namespace std;
void permutation(int* a,int length)
{
int i,flag;
sort(a,a+length);
do
{
for(i=0;i<length;i++)
{
if(a[i]==3)
flag=1;
else if(a[i]==4) //如果3在4的左边,执行完代码,flag就是2
flag=2;
}
if(flag==1) //如果4在3的左边,执行完代码,flag就是1
{
for(i=0;i<length;i++)
cout<<a[i];
cout<<endl;
}
}while(next_permutation(a,a+length));
}
int main(void)
{
int i,a[5];
for(i=0;i<5;i++)
a[i]=i+1;
printf("%d以内所有4在3左边的全排列结果为:\n",i);
permutation(a,5);
system("pause");
return 0;
}
另外next_permutation在达到逆序最大值后,会返回false,并且将按字典升序排序;
int list[3]={3,2,1};
next_permutation(list,list+3);
cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
//输出: 1 2 3