递归基础_全排列(一般递推实现)

C: 全排列问题

描述

生成一个1..N的全排列. 

输入

第一行包括一个数字 n 小于 9

输出

按字典序输出1...N的所有全排列.

样例

输入: 3

输出: 123 132 213 231 312 321(a,b,c)

状态转移方程为: A(n, n)=A(n,1)(组合+)A(n-1,1)....A(1,1)

实现全排列和组合不一样的地方在于,对于(a,b,c)——(a,b)的遍历 不需要设置 a (表头)的上限,

只需要要求已经置入的数不再重复即可——因为组合可以用上界来限制,而这个表达比较困难,所以用bool数组标记来表示

代码如下:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <queue>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <map>
 7 #include <algorithm>
 8 typedef long long ll;
 9 using namespace std;
10 int n;
11 int a[11];
12 bool x[11];
13 void f(int it,int num) {
14 //num表示此时已经排列了几层(栈的深度)
15 //it表示下一个要压入的数
16     a[num]=it;//入栈
17     x[it]=1;//mark
18     if(num==n) {
19         for(int j=1; j<=n; j++) {
20             cout<<a[j]<<" ";
21         }
22         printf("\n");
23     } else {
24         for(int i=1; i<=n; i++) {
25             if(x[i]==1)continue;
26             else f(i,num+1);
27         }
28     }
29     x[it]=0;
30 }
31 
32 int main () {
33     cin>>n;
34     memset(x,0,sizeof(x));
35     for(int i=1; i<=n; i++) {
36         f(i,1);
37     }
38 
39     return 0;
40 }
View Code

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/KID-yln/p/12529307.html