從數組中取出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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM