permutation and combination

本文介绍了使用递归实现的排列和组合算法,并对比了STL中next_permutation的实现方式。通过具体的C++代码示例,展示了如何生成指定长度的排列和组合。

排列组合,自己也尝试着写过,用的深搜,但不是字典序的。

看了浙大的acm集训资料,其中排列和组合的算法,不错,贴出来~~

 

 #include <iostream>

using namespace std;

const int MAXN = 100;
int count;
void _gen_perm(int *a, int n, int m,int l,int *tag,int *tmp)
{
if(l == m)
dummy(tmp,m);
else
{
for(int i = 0; i < n; ++i)
{
if(!tag[i])
{
tmp[l] = a[i];
tag[i] = 1;
_gen_perm(a,n,m,l+1,tag,tmp);
//回溯法
tag[i] = 0;
}
}
}
}

//生成排列,字典序
void gen_perm(int n,int m)
{
int a[MAXN],tmp[MAXN],tag[MAXN] = {0};
for(int i = 0; i < n; ++i)
{
a[i] = i+1;
}
_gen_perm(a,n,m,0,tag,tmp);
}

void _gen_comb(int *a,int s,int e,int m,int *tmp,int &pos)
{
if(!m)
{
dummy(tmp,pos);
}
else
{
for(int i = s; i < e-m + 1; ++i)
{
tmp[pos++] = a[i];
_gen_comb(a,i+1,e,m-1,tmp,pos);
pos--;
}
}
}


void gen_comb(int n,int m)
{
int a[MAXN],tmp[MAXN];
int pos = 0;
for(int i = 0; i < n; ++i)
{
a[i] = i +1;
}
_gen_comb(a,0,n,m,tmp,pos);
}


int main()
{
cout << "permutation:" << endl;
gen_perm(4,2);
cout << "combiation:" << endl;
gen_comb(4,2);
return 0;
}

 

另外,还有c++ stl 中也有关于排列的算法,看了stl源码剖析,感觉很赞~~~~

这两个函数是 next_permutation,prev_permutation。

 

我照着写了一个,贴出来,prve_permutation 类似,就不贴了。

 template<typename BidirectionIterator>

bool next_permutation(BidirectionIterator first, BidirectionIterator last)

{

//there is no items

if(first == last)

return false;

// this is only one items

BidirectionIterator i = first;

++i;

if(i == last)

return false;

i = last;

--i;


for(;;)

{

BidirectionIterator ii =i;

--i;

if(*i < *ii)

{

BidirectionIterator j = last;

while(!(*i < *--j));

std::iter_swap(i,j);

std::reverse(ii,last);

return true;

}

if(i == first)

{

std::reverse(first,last);

return false;

}

}

}

 

感觉stl的算法简短些,不过功能也弱些~~~ 

转载于:https://www.cnblogs.com/liangxiufei/archive/2009/11/14/1603123.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值