在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 }

解决相同问题的其他方法可以通过检查组合中是否包含当前元素并打印所需大小的所有组合来实现。想法是一样的,我们将遍历元素并将组合存储在组合数组中。但是元素的固定没有完成。

以下程序将使您更容易理解问题-

示例

#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 }