1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stdbool.h> 4 5 int Combine(const int const arr[], const int n, const int m) 6 { 7 #define MAX_COMBINE_M 10 8 #define MAX_COMBINE_N 10 9 10 if (m > MAX_COMBINE_M || n > MAX_COMBINE_N) { 11 printf("OverSize!\n"); 12 return 0; 13 } 14 unsigned int i; 15 bool printFlag = false; 16 unsigned int curPos = 0; /* 指示pick数组的当前下标 */ 17 unsigned int cnt = 0; 18 unsigned int *pick = (unsigned int *)malloc(sizeof(unsigned int) * m); /* 保存从arr中选取的元素下标 */ 19 20 for (i = 0; i < m; i++) { 21 pick[i] = 0; 22 } 23 24 while (pick[0] + m <= n + 1) { /* C(m,n)全部组合选取完毕判断条件 */ 25 if (printFlag) { 26 for (i = 0; i < m; i++) { 27 printf("%d ", arr[pick[i] - 1]); 28 } 29 printf("\n"); 30 printFlag = false; 31 cnt++; 32 } 33 34 pick[curPos]++; /* 选取arr中下一个元素, 值为1对应arr数组下标0 */ 35 if (pick[curPos] == n + 1) { /* 当前位置无元素可选,回溯 */ 36 pick[curPos] = 0; 37 curPos--; 38 continue; 39 } 40 41 if (curPos < m - 1) { /* 还有剩余位置未选取,选取下一个元素 */ 42 curPos++; 43 pick[curPos] = pick[curPos - 1]; /* 防止重复,当前位置的元素选取从上一个位置的元素的开始 */ 44 continue; 45 } 46 47 if (curPos == m - 1) { /* m个元素选取完毕 */ 48 printFlag = true; 49 } 50 } 51 free(pick); 52 return cnt; 53 } 54 55 int main() 56 { 57 #define N 5; 58 #define M 3; 59 int a[] = {0, 1, 2, 3, 4}; 60 61 printf("cnt = %d\n", Combine(a, N, M)); 62 63 return 0; 64 }View Code