Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 크기가 n인 주어진 배열에서 r 요소의 가능한 모든 조합을 인쇄합니다.

<시간/>

이 문제에서는 크기가 n인 배열과 양의 정수 r이 제공됩니다. 우리의 임무는 sizer 배열 요소의 가능한 모든 조합을 인쇄하는 것입니다.

문제를 이해하기 위해 예를 들어 보겠습니다 -

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 }