Paste Search Dynamic
Recent pastes
print all combination of size
  1. /* HANDLING DUPLICATES:
  2.         // Since the elements are sorted, all occurrences of an element
  3.         // must be together
  4.         while (arr[i] == arr[i+1])
  5.              i++;
  6. */
  7.  
  8. // C++ program to print all combination
  9. // of size r in an array of size n
  10. #include<bits/stdc++.h>
  11. using namespace std;
  12.  
  13. void combinationUtil(int arr[], int data[],
  14.                                         int start, int end,
  15.                                         int index, int r);
  16.  
  17. // The main function that prints
  18. // all combinations of size r
  19. // in arr[] of size n. This function
  20. // mainly uses combinationUtil()
  21. void printCombination(int arr[], int n, int r)
  22. {
  23.         // A temporary array to store
  24.         // all combination one by one
  25.         int data[r];
  26.  
  27.         // Print all combination using
  28.         // temprary array 'data[]'
  29.         combinationUtil(arr, data, 0, n-1, 0, r);
  30. }
  31.  
  32. /* arr[] ---> Input Array
  33. data[] ---> Temporary array to
  34. store current combination
  35. start & end ---> Staring and
  36. Ending indexes in arr[]
  37. index ---> Current index in data[]
  38. r ---> Size of a combination to be printed */
  39. void combinationUtil(int arr[], int data[],
  40.                                         int start, int end,
  41.                                         int index, int r)
  42. {
  43.         // Current combination is ready
  44.         // to be printed, print it
  45.         if (index == r)
  46.         {
  47.                 for (int j = 0; j < r; j++)
  48.                         cout << data[j] << " ";
  49.                 cout << endl;
  50.                 return;
  51.         }
  52.  
  53.         // replace index with all possible
  54.         // elements. The condition "end-i+1 >= r-index"
  55.         // makes sure that including one element
  56.         // at index will make a combination with
  57.         // remaining elements at remaining positions
  58.         for (int i = start; i <= end &&
  59.                 end - i + 1 >= r - index; i++)
  60.         {
  61.                 data[index] = arr[i];
  62.                 combinationUtil(arr, data, i+1,
  63.                                                 end, index+1, r);
  64.         }
  65. }
  66.  
  67. // Driver code
  68. int main()
  69. {
  70.         int arr[] = {1, 2, 3, 4, 5};
  71.         int r = 3;
  72.         int n = sizeof(arr)/sizeof(arr[0]);
  73.         printCombination(arr, n, r);
  74. }
  75.  
Parsed in 0.014 seconds