排列和组合算法

排列和组合算法是考查递归的常见算法,这两种算法能用递归简洁地实现。

本人在经过多次摸索和思考之后,总结如下,以供参考。

程序代码如下:


 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 char array[] = "abcd";
 5 
 6 #define N  4
 7 #define M  3
 8 int queue[N] = {0};
 9 int top = 0;
10 int flag[N] = {0};
11 
12 void perm(int s, int n)
13 {
14     int i;
15 
16     if (s > n)
17     {
18         return;
19     }
20 
21     if (s == n)
22     {
23         for (i = 0; i < n; i++)
24         {
25             printf("%c", queue[i]);
26         }
27         printf("\t");
28         return ;
29     }
30 
31     for (i = 0; i < n; i++)
32     {
33         if (flag[i] == 0)
34         {
35             flag[i] = 1;
36             queue[s] = array[i];
37             perm(s+1, n);
38             flag[i] = 0;
39         }
40     }
41 }
42 
43 void comb(int s, int n, int m)
44 {
45     int i;
46 
47     if (s > n)
48         return ;
49 
50     if (top == m)
51     {
52         for (i = 0; i < m; i++)
53         {
54             printf("%c", queue[i]);
55         }
56         printf("\t");
57         return ;
58     }
59 
60     queue[top++] = array[s];
61     comb(s+1, n, m);
62     top--;
63     comb(s+1, n, m);
64 
65 }
66 
67 int main()
68 {
69     printf("\nperm():\n");
70     perm(0, N);
71     printf("\ncombination():\n");
72     comb(0, N, M);
73     printf("\n");
74     return 0;

75 }


运行结果:

perm():
abcd    abdc    acbd    acdb    adbc    adcb    bacd    badc    bcad    bcda
bdac    bdca    cabd    cadb    cbad    cbda    cdab    cdba    dabc    dacb
dbac    dbca    dcab    dcba
combination():
abc     abd     acd     bcd
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值