从数组中取出N个元素的所有组合——递归实现

https://www.cnblogs.com/null00/archive/2012/04/27/2473788.html

今天在做POJ 1753时,需要枚举一个数组中所有组合。之前也遇到过类似的问题,如求从n个数组任意选取一个元素的所有组合都是想起来比较简单,但是设计成算法却颇费周折。
如数组为{1, 2, 3, 4, 5, 6},那么从它中取出3个元素的组合有哪些,取出4个元素的组合呢?
比如取3个元素的组合,我们的思维是:
取1、2,然后再分别取3,4,5,6;
取1、3,然后再分别取4,5,6;
......
取2、3,然后再分别取4,5,5;
......
这样按顺序来,就可以保证完全没有重复。

这种顺序思维给我们的启示便是这个问题可以用递归来实现,但是仅从上述描述来看,却无法下手。
我们可以稍作改变:
1.先从数组中A取出一个元素,然后再从余下的元素B中取出一个元素,然后又在余下的元素C中取出一个元素
2.按照数组索引从小到大依次取,避免重复

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<string>
 6 #include<assert.h>
 7 using namespace std;
 8 const int maxn = 10010;
 9 const int inf = 0x3f3f3f;
10 typedef long long ll;
11 //a为原始数组
12 //start为遍历起始位置
13 //result保存结果,为一维数组
14 //count为result数组的索引值,起辅助作用
15 //num为要选取的元素个数
16 //a_len为原始数组的长度,为定值
17 void combine_increase(int* a, int start, int* result, int count, const int num,const int a_len)
18 {//从小到大进行遍历
19     int i = 0;
20     for (i = start; i < a_len + 1 - count; i++)
21     {
22         result[count - 1] = i;
23         if (count - 1 == 0)
24         {
25             int j;
26             for (j = num - 1; j >= 0; j--)
27             {
28                 printf("%d\t", a[result[j]]);
29             }
30             printf("\n");
31         }
32         else
33         {
34             combine_increase(a, i + 1, result, count - 1, num, a_len);
35         }
36     }
37 }
38 //a为原始数组
39 //start为遍历起始位置
40 //result保存结果,为一维数组
41 //count为result数组的索引值,起辅助作用
42 //num为要选取的元素个数
43 void combine_decrease(int* a, int start, int* result, int count, const int num)
44 {//从大到小进行遍历
45     int i;
46     for (i = start; i >= count; i--)
47     {
48         result[count - 1] = i - 1;
49         if (count > 1)
50         {
51             combine_decrease(a, i - 1, result, count - 1, num);
52         }
53         else
54         {
55             int j;
56             for (j = num - 1; j >= 0; j--)
57             {
58                 printf("%d\t", a[result[j]]);
59             }
60             printf("\n");
61         }
62     }
63 }
64 int main()
65 {
66     int a[] = { 1,2,3,4,5,6 };
67     int num = 4;
68     int result[4];
69     combine_increase(a, 0, result, num, num, sizeof a / sizeof(int));
70     printf("分界线\n");
71     combine_decrease(a, sizeof a / sizeof(int), result, num, num);
72     return 0;
73 }

 

posted @ 2019-04-15 16:59  Fzzf1  阅读(2369)  评论(0编辑  收藏  举报