注册 登录
编程论坛 C++教室

[求助]如何编程实现全排列

shenderong 发布于 2007-07-04 11:43, 1428 次点击

比如 代码中const int N=3;
输出结果:

123
132
213
231
312
321

代码中const int N=4;
输出结果:

1234
1243
1324
1342
...
...
...


[此贴子已经被作者于2007-7-4 11:44:19编辑过]

7 回复
#2
aipb20072007-07-04 11:49
用next_permutation()

要自己写的话,看原理,我blog里有。
https://blog.bc-cn.net/user20/130988/archives/2007/6553.shtml
#3
shenderong2007-07-04 11:55
谢拉!
我起初只想锻炼一下能力的,觉得太难编了,没想到还有库函数啊,看来还有很多东西要看.
#4
HJin2007-07-04 11:59
hoho, aipb now owns a blog.

congrats!

#5
aipb20072007-07-04 12:03
很早就有啦,没用!
呵呵~什么都没有!

>_<
#6
HJin2007-07-04 12:42
good good study
day day up
#7
HJin2007-07-04 13:11
回复:(shenderong)[求助]如何编程实现全排列

/*---------------------------------------------------------------------------
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;
}

#8
shenderong2007-07-04 23:55
真是太感谢7楼的高手了

英文也那么好 我会收藏这段程序
1