轉載:
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