比如 代码中const int N=3;
输出结果:
123
132
213
231
312
321
代码中const int N=4;
输出结果:
1234
1243
1324
1342
...
...
...
[此贴子已经被作者于2007-7-4 11:44:19编辑过]
/*---------------------------------------------------------------------------
File name: AllPerm.cpp
Author: HJin (email: fish_sea_bird[at]yahoo.com)
Created on: 7/3/2007 22:05:45
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
Analysis:
---------------------------------------------------------------------------
Since you asked for help, I provide this source code
for you to play with.
I deleted comments for each function on purpose --- so that
you will have to study the code to understand the idea.
A minor flaw with this implementation is that it does not output
the permuations in "lexicographic order". If you wish, you could use
two or more buffers (here we only used one buffer a[]) to do it in
"lexicographic order".
This implementation is based on recursion. You could do it by an iterative
way. Iteration approach, AFAIK, is hard to understand for a beginner.
Sample output:
---------------------------------------------------------------------------
#1: 1234
#2: 1243
#3: 1342
#4: 1324
#5: 1423
#6: 1432
#7: 2341
#8: 2314
#9: 2413
#10: 2431
#11: 2134
#12: 2143
#13: 3412
#14: 3421
#15: 3124
#16: 3142
#17: 3241
#18: 3214
#19: 4123
#20: 4132
#21: 4231
#22: 4213
#23: 4312
#24: 4321
Press any key to continue . . .
Reference:
---------------------------------------------------------------------------
*/
#include <iostream>
using namespace std;
#define N 4
int a[N] = {1, 2, 3, 4};
void do_permute(int m);
void permute();
void rotate(int m);
int main(int argc, char** argv)
{
permute();
return 0;
}
void do_permute(int m)
{
static int counter = 0;
if(m==0)
{
++counter;
cout<<"#"<<counter<<":\t";
for(int i=0; i<N; ++i)
{
cout<<a[i];
}
cout<<endl;
return;
}
for(int i=0; i<m; ++i)
{
do_permute(m-1);
rotate(m);
}
}
void permute()
{
do_permute(N);
}
void rotate(int m)
{
int temp = a[N-m];
for(int j=N-m; j<N-1; ++j)
a[j] = a[j+1];
a[N-1] = temp;
}