1. 程式人生 > >【演算法-分治】從陣列中取出n個元素的所有組合(需要深入理解遞迴)

【演算法-分治】從陣列中取出n個元素的所有組合(需要深入理解遞迴)

本文為轉載,原文章出處http://www.cnblogs.com/shuaiwhu/archive/2012/04/27/2473788.html

如陣列為{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 //arr為原始陣列
 2 //start為遍歷起始位置
 3 //result儲存結果,為一維陣列
 4 //count為result陣列的索引值,起輔助作用
 5 //NUM為要選取的元素個數
 6 //arr_len為原始陣列的長度,為定值
 7 void combine_increase(int* arr, int start, int* result, int count, const int NUM, const int arr_len)
 8 {
 9   int i = 0;
10   for (i = start; i < arr_len + 1
- count; i++) 11 { 12 result[count - 1] = i; 13 if (count - 1 == 0) 14 { 15 int j; 16 for (j = NUM - 1; j >= 0; j--) 17 printf("%d\t",arr[result[j]]); 18 printf("\n"); 19 } 20 else 21 combine_increase(arr, i + 1, result, count - 1, NUM, arr_len);
22 } 23 }
複製程式碼

當然,我們也可以按照索引從大到小進行遍歷:

複製程式碼
 1 //arr為原始陣列
 2 //start為遍歷起始位置
 3 //result儲存結果,為一維陣列
 4 //count為result陣列的索引值,起輔助作用
 5 //NUM為要選取的元素個數
 6 void combine_decrease(int* arr, int start, int* result, int count, const int NUM)
 7 {
 8   int i;
 9   for (i = start; i >=count; i--)
10   {
11     result[count - 1] = i - 1;
12     if (count > 1)
13     {
14       combine_decrease(arr, i - 1, result, count - 1, NUM);
15     }
16     else
17     {
18       int j;
19       for (j = NUM - 1; j >=0; j--)
20     printf("%d\t",arr[result[j]]);
21       printf("\n");
22     }
23   }
24 }
複製程式碼

測試程式碼:

複製程式碼
 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5   int arr[] = {1, 2, 3, 4, 5, 6};
 6   int num = 4;
 7   int result[num];
 8 
 9   combine_increase(arr, 0, result, num, num, sizeof(arr)/sizeof(int));
10   printf("分界線\n");
11   combine_decrease(arr, sizeof(arr)/sizeof(int), result, num, num);
12   return 0;
13 }
複製程式碼

改進:我的方法

#include<iostream>
using namespace std;
void combine_increase(int* arr, int start, int* result, int count, const int NUM, const int arr_len)
 {
   int i = 0;
   for (i = start; i < arr_len + 1 - count; i++)
   {
     result[count - 1] = i;
     if (count - 1 == 0)
     {
       int j;
      for (j = NUM - 1; j >= 0; j--)
        printf("%d\t",arr[result[j]]);
       printf("\n");
     }
     else
       combine_increase(arr, i + 1, result, count - 1, NUM, arr_len);
   }
 }
 
 int main()
  {
  printf("請輸入您要輸入的陣列?以-123結束\n");
int *arr=new int;
int i=0;
scanf("%d",&arr[i]);
while(arr[i]!=-123)
{
i++;
printf("請輸入您要輸入的陣列?以-123結束\n");
scanf("%d",&arr[i]);
}
printf("請輸入要找幾個數字的所有組合?\n");
int total;
scanf("%d",&total);
int *data=new int[total];//儲存組合數
int len=i;
   combine_increase(arr, 0, data, total, total, len);
   return 0;
 }

結果: