近日在维普数据库里看资料,偶然发现了一个介绍组合生成算法的文章,照着算法流程,自己写了一下,发现速度果然不错。
C++实现代码:
#include
<
cstdlib
>
#include < iostream >
using namespace std;
void combination( int n, int m ) ... {
int *A=new int[n+1];
int *B=new int[m+1];
int i, j;
for( i=1; i<=n; ++i )
A[i]=i;
for( i=1; i<=m; ++i )
B[i]=m;
while( B[1]<n )...{
for( i=1; i<=m; ++i )
cout<<A[i]<<" ";
cout<<endl;
j=m;
while( B[j]==n )
--j;
++B[j];
for( i=j+1; i<=m; ++i )
B[i]=B[j];
swap( A[j], A[B[j]] );
}
delete []A;
delete []B;
}
int main( int argc, char * argv[])
... {
combination( 20, 4 );
system("PAUSE");
return EXIT_SUCCESS;
}
#include < iostream >
using namespace std;
void combination( int n, int m ) ... {
int *A=new int[n+1];
int *B=new int[m+1];
int i, j;
for( i=1; i<=n; ++i )
A[i]=i;
for( i=1; i<=m; ++i )
B[i]=m;
while( B[1]<n )...{
for( i=1; i<=m; ++i )
cout<<A[i]<<" ";
cout<<endl;
j=m;
while( B[j]==n )
--j;
++B[j];
for( i=j+1; i<=m; ++i )
B[i]=B[j];
swap( A[j], A[B[j]] );
}
delete []A;
delete []B;
}
int main( int argc, char * argv[])
... {
combination( 20, 4 );
system("PAUSE");
return EXIT_SUCCESS;
}