全排列算法及实现

转载:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值