排列组合,自己也尝试着写过,用的深搜,但不是字典序的。
看了浙大的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的算法简短些,不过功能也弱些~~~