在 C++ 中列印給定大小為 n 的陣列中 r 個元素的所有可能組合


在這個問題中,我們給定一個大小為 n 的陣列和一個正整數 r。我們的任務是列印大小為 r 的陣列元素的所有可能組合。

讓我們舉個例子來理解這個問題:

Input: {5,6,7,8} ; r = 3
Output : {5,6,7}, {5,6,8}, {5,7,8}, {6,7,8}

解決這個問題的一種方法是固定元素,然後遞迴或迴圈遍歷其他元素以找到所有組合。在這裡,我們只需要固定前 **n-r+1** 個元素,然後迴圈或遞迴遍歷其餘元素。

示例

#include<iostream>
using namespace std;
void printRElementCombination(int arr[], int combination[], int start, int
end, int index, int r){
   if (index == r){
      cout<<"{ ";
      for (int j = 0; j < r; j++)
         cout << combination[j] << " ";
         cout<<"}\t";
      return;
   }
   for (int i = start; i <= end && end - i + 1 >= r - index; i++){
      combination[index] = arr[i];
      printRElementCombination(arr, combination, i+1, end, index+1, r);
   }
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int r = 3;
   int n = 5;
   int combination[r];
   cout<<"The combination is : \n";
   printRElementCombination(arr, data, 0, n-1, 0, r);
}

輸出

組合是:

{ 1 2 3 } { 1 2 4 } { 1 2 5 } { 1 3 4 } { 1 3 5 } { 1 4 5 }
{ 2 3 4 } { 2 3 5 } { 2 4 5 } { 3 4 5 }

解決同一問題的其他方法是檢查組合中當前元素的包含情況,並列印所有所需大小的組合。其思想相同,我們將遞迴遍歷元素並將組合儲存在 combo 陣列中。但是,不會固定元素。

下面的程式將使您更容易理解這個問題:

示例

即時演示

#include <iostream>
using namespace std;
void combinationUtil(int arr[], int n, int r, int index, int combo[], int i){
   if (index == r){
      cout<<"{";
      for (int j = 0; j < r; j++)
         cout << combo[j] << " ";
         cout<<"}\t";
         return;
   }
   if (i >= n)
      return;
   combo[index] = arr[i];
   combinationUtil(arr, n, r, index + 1, combo, i + 1);
   combinationUtil(arr, n, r, index, combo, i+1);
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int r = 3;
   int n = 5;
   int combo[r];
   cout<<"The combination is : \n";
   combinationUtil(arr, n, r, 0, combo, 0);
   return 0;
}

輸出

組合是:

{1 2 3 }    {1 2 4 }    {1 2 5 }    {1 3 4 }    {1 3 5 }    {1 4 5 }
      {2 3 4 }    {2 3 5 }    {2 4 5 }     {3 4 5 }

更新於:2020年1月17日

2K+ 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告