本算法与上一篇的组合生成算法是一体的,也是在维普上看到的。我用C++实现如下:
#include
<
cstdlib
>
#include < iostream >
#include < iterator >
using namespace std;
void Permutation( int n ) ... {
int *A=new int[n+1], *B=new int[n+1], i=0, j;
for( j=1; j<=n; ++j )
A[j]=j, B[j]=0;
while( i!=n+1 )...{
copy(A+1,A+n+1,ostream_iterator<int>(cout," "));
cout<<endl;
for( i=2; i<=n && B[i]>=i-1 ; ++i );
++B[i];
if( i&1 ) swap( A[i], A[1] );
else swap( A[i], A[B[i]] );
for( j=1; j<=i-1; ++j )
B[j]=0;
}
delete []A; delete []B;
}
int main( int argc, char * argv[]) ... {
Permutation( 4 );
system("PAUSE");
return EXIT_SUCCESS;
}
#include < iostream >
#include < iterator >
using namespace std;
void Permutation( int n ) ... {
int *A=new int[n+1], *B=new int[n+1], i=0, j;
for( j=1; j<=n; ++j )
A[j]=j, B[j]=0;
while( i!=n+1 )...{
copy(A+1,A+n+1,ostream_iterator<int>(cout," "));
cout<<endl;
for( i=2; i<=n && B[i]>=i-1 ; ++i );
++B[i];
if( i&1 ) swap( A[i], A[1] );
else swap( A[i], A[B[i]] );
for( j=1; j<=i-1; ++j )
B[j]=0;
}
delete []A; delete []B;
}
int main( int argc, char * argv[]) ... {
Permutation( 4 );
system("PAUSE");
return EXIT_SUCCESS;
}