The Wayback Machine - https://web.archive.org/web/20240917134516/https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/
Open In App

Print all combinations | Set-2

Last Updated : 28 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of size n, generate and print all possible combinations of r elements in the array.

Example:

Input: arr=[1,2,3,4], r=2

Output: 1 2
1 3
1 4
2 3
2 4
3 4

Input: arr=[1,2,3,4], r=3

Output: 1 2 3
1 2 4
1 3 4
2 3 4

Method 1 (Fix Elements and Recur) 

The idea is to start from first index (index = 0) , one by one fix elements at this index and recur for remaining indexes. Let the input array be {1, 2, 3, 4, 5} and r be 3. We first fix 1 at index 0, then recur for remaining indexes, then we fix 2 at index 0 and recur. Finally, we fix 3 and recur for remaining indexes. When number of elements becomes equal to r (size of a combination), we print them.

Following diagram shows recursion tree for same input. 


 Following is the implementation of the above approach.  

C++

// C++ program to print all combination // of size r in an array of size n #include<bits/stdc++.h> using namespace std; void combinationUtil(int arr[], int data[], int start, int end, int index, int r); // The main function that prints // all combinations of size r // in arr[] of size n. This function // mainly uses combinationUtil() void printCombination(int arr[], int n, int r) { // A temporary array to store // all combination one by one int data[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << " "; cout << endl; return; } // replace index with all possible // elements. The condition "end-i+1 >= r-index" // makes sure that including one element // at index will make a combination with // remaining elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // Driver code int main() { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); } // This code is contributed by rathbhupendra

C

// Program to print all combination of size r in an array of size n #include <stdio.h> void combinationUtil(int arr[], int data[], int start, int end, int index, int r); // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) printf("%d ", data[j]); printf("\n"); return; } // replace index with all possible elements. The condition // "end-i+1 >= r-index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // Driver program to test above functions int main() { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); }

Java

// Java program to print all combination of size r in an array of size n import java.io.*; class Combination { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) System.out.print(data[j]+" "); System.out.println(""); return; } // replace index with all possible elements. The condition // "end-i+1 >= r-index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[]=new int[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = arr.length; printCombination(arr, n, r); } } /* This code is contributed by Devesh Agrawal */

C#

// C# program to print all // combination of size r // in an array of size n using System; class GFG { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int []data, int start, int end, int index, int r) { // Current combination is // ready to be printed, // print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + " "); Console.WriteLine(""); return; } // replace index with all // possible elements. The // condition "end-i+1 >= // r-index" makes sure that // including one element // at index will make a // combination with remaining // elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); } } // The main function that prints // all combinations of size r // in arr[] of size n. This // function mainly uses combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store // all combination one by one int []data = new int[r]; // Print all combination // using temporary array 'data[]' combinationUtil(arr, data, 0, n - 1, 0, r); } // Driver Code static public void Main () { int []arr = {1, 2, 3, 4, 5}; int r = 3; int n = arr.Length; printCombination(arr, n, r); } } // This code is contributed by m_kit

JavaScript

<script> // Javascript program to print all // combination of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr,data,start,end,index,r) { // Current combination is ready to be printed, print it if (index == r) { for (let j=0; j<r; j++) { document.write(data[j]+" "); } document.write("<br>") } // replace index with all possible elements. The condition // "end-i+1 >= r-index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (let i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() function printCombination(arr,n,r) { // A temporary array to store all combination one by one let data = new Array(r); // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /*Driver function to check for above function*/ let arr=[1, 2, 3, 4, 5]; let r = 3; let n = arr.length; printCombination(arr, n, r); // This code is contributed by rag2127 </script>

PHP

<?php // Program to print all // combination of size r // in an array of size n // The main function that // prints all combinations // of size r in arr[] of // size n. This function // mainly uses combinationUtil() function printCombination($arr, $n, $r) { // A temporary array to // store all combination // one by one $data = array(); // Print all combination // using temporary array 'data[]' combinationUtil($arr, $data, 0, $n - 1, 0, $r); } /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil($arr, $data, $start, $end, $index, $r) { // Current combination is ready // to be printed, print it if ($index == $r) { for ($j = 0; $j < $r; $j++) echo $data[$j]; echo "\n"; return; } // replace index with all // possible elements. The // condition "end-i+1 >= // r-index" makes sure that // including one element at // index will make a combination // with remaining elements at // remaining positions for ($i = $start; $i <= $end && $end - $i + 1 >= $r - $index; $i++) { $data[$index] = $arr[$i]; combinationUtil($arr, $data, $i + 1, $end, $index + 1, $r); } } // Driver Code $arr = array(1, 2, 3, 4, 5); $r = 3; $n = sizeof($arr); printCombination($arr, $n, $r); // This code is contributed by ajit ?>

Python3

# Program to print all combination # of size r in an array of size n # The main function that prints # all combinations of size r in # arr[] of size n. This function # mainly uses combinationUtil() def printCombination(arr, n, r): # A temporary array to # store all combination # one by one data = [0]*r; # Print all combination # using temporary array 'data[]' combinationUtil(arr, data, 0, n - 1, 0, r); # arr[] ---> Input Array # data[] ---> Temporary array to # store current combination # start & end ---> Starting and Ending # indexes in arr[] # index ---> Current index in data[] # r ---> Size of a combination # to be printed def combinationUtil(arr, data, start, end, index, r): # Current combination is ready # to be printed, print it if (index == r): for j in range(r): print(data[j], end = " "); print(); return; # replace index with all # possible elements. The # condition "end-i+1 >= # r-index" makes sure that # including one element at # index will make a combination # with remaining elements at # remaining positions i = start; while(i <= end and end - i + 1 >= r - index): data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); i += 1; # Driver Code arr = [1, 2, 3, 4, 5]; r = 3; n = len(arr); printCombination(arr, n, r); # This code is contributed by mits


Output

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

Time Complexity: [Tex]{n \choose r} [/Tex]
Auxiliary Space: O(r). We use a temporary array data[] of size r to store current combination.

Method 2: Include and Exclude every element

The idea is to explore each element in the array, considering whether to include it or skip it in the current combination. When the combination size reaches r, it’s printed, and this process continues recursively for all elements, ensuring that every valid combination is discovered.

Step-by-step approach:

  • Create a temporary array data[].
  • One by one consider every element of input array, and recur for two cases:
    • The element is included in current combination (We put the element in data[] and increment next available index in data[]) 
    • The element is excluded in current combination (We do not put the element and do not change index)
  • When number of elements in data[] become equal to r (size of a combination), we print it.

Below is the implementation of the above approach:

C++

// C++ Program to print all combination of // size r in an array of size n #include <bits/stdc++.h> using namespace std; void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all // combinations of size r in arr[] // of size n. This function mainly // uses combinationUtil() void printCombination(int arr[], int n, int r) { // A temporary array to store // all combination one by one int data[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */ void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << " "; cout << endl; return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // Driver code int main() { int arr[] = {1, 2, 4, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0; } // This is code is contributed by rathbhupendra

C

// Program to print all combination of size r in an array of size n #include<stdio.h> void combinationUtil(int arr[],int n,int r,int index,int data[],int i); // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */ void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready, print it if (index == r) { for (int j=0; j<r; j++) printf("%d ",data[j]); printf("\n"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // Driver program to test above functions int main() { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0; }

Java

// Java program to print all combination of size r in an array of size n import java.io.*; class Combination { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) System.out.print(data[j]+" "); System.out.println(""); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[]=new int[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = arr.length; printCombination(arr, n, r); } } /* This code is contributed by Devesh Agrawal */

C#

// C# program to print all // combination of size r // in an array of size n using System; class GFG { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int n, int r, int index, int []data, int i) { // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + " "); Console.WriteLine(""); return; } // When no more elements are // there to put in data[] if (i >= n) return; // current is included, put // next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that // i+1 is passed, but index // is not changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints // all combinations of size r // in arr[] of size n. This // function mainly uses combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store // all combination one by one int []data = new int[r]; // Print all combination // using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } // Driver Code static public void Main () { int []arr = {1, 2, 3, 4, 5}; int r = 3; int n = arr.Length; printCombination(arr, n, r); } } // This code is contributed by ajit

JavaScript

<script> // Javascript program to print all // combination of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr,n,r,index,data,i) { // Current combination is ready // to be printed, print it if (index == r) { for (let j=0; j<r; j++) { document.write(data[j]+" "); } document.write("<br>"); return; } // When no more elements are there // to put in data[] if (i >= n) { return; } // current is included, put // next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace // it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // The main function that prints // all combinations of size r // in arr[] of size n. This function // mainly uses combinationUtil() function printCombination(arr,n,r) { // A temporary array to store // all combination one by one let data=new Array(r); // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /*Driver function to check for above function*/ let arr=[1, 2, 3, 4, 5]; let r = 3; let n = arr.length; printCombination(arr, n, r); // This code is contributed by avanitrachhadiya2155 </script>

PHP

<?php // Program to print all // combination of size r // in an array of size n // The main function that prints // all combinations of size r in // arr[] of size n. This function // mainly uses combinationUtil() function printCombination($arr, $n, $r) { // A temporary array to store // all combination one by one $data = Array(); // Print all combination using // temporary array 'data[]' combinationUtil($arr, $n, $r, 0, $data, 0); } /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */ function combinationUtil($arr, $n, $r, $index, $data, $i) { // Current combination // is ready, print it if ($index == $r) { for ($j = 0; $j < $r; $j++) echo $data[$j], " "; echo "\n"; return; } // When no more elements are // there to put in data[] if ($i >= $n) return; // current is included, put // next at next location $data[$index] = $arr[$i]; combinationUtil($arr, $n, $r, $index + 1, $data, $i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not changed) combinationUtil($arr, $n, $r, $index, $data, $i + 1); } // Driver Code $arr = array(1, 2, 3, 4, 5); $r = 3; $n = sizeof($arr); printCombination($arr, $n, $r); // This code is contributed by ajit ?>

Python 3

# Program to print all combination # of size r in an array of size n # The main function that prints all # combinations of size r in arr[] of # size n. This function mainly uses # combinationUtil() def printCombination(arr, n, r): # A temporary array to store # all combination one by one data = [0] * r # Print all combination using # temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0) ''' arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] ''' def combinationUtil(arr, n, r, index, data, i): # Current combination is ready, # print it if (index == r): for j in range(r): print(data[j], end = " ") print() return # When no more elements are # there to put in data[] if (i >= n): return # current is included, put # next at next location data[index] = arr[i] combinationUtil(arr, n, r, index + 1, data, i + 1) # current is excluded, replace it # with next (Note that i+1 is passed, # but index is not changed) combinationUtil(arr, n, r, index, data, i + 1) # Driver Code if __name__ == "__main__": arr = [1, 2, 3, 4, 5] r = 3 n = len(arr) printCombination(arr, n, r) # This code is contributed # by ChitraNayal


Output

1 2 4 1 2 4 1 2 5 1 4 4 1 4 5 1 4 5 2 4 4 2 4 5 2 4 5 4 4 5

Time Complexity: O(2n)
Auxiliary Space : O(r)

Method 3: Handling Duplicates

Note that the above method doesn’t handle duplicates. For example, if input array is {1, 2, 1} and r is 2, then the program prints {1, 2} and {2, 1} as two different combinations. We can avoid duplicates by adding following two additional things to above code.

  • 1) Add code to sort the array before calling combinationUtil() in printCombination() 
  • 2) If the current element is equal to previous element we simply skip that element.

Below is the implementation of above approach:

C++

// Program to print all combination of size r in an array of size n #include <stdio.h> #include <stdlib.h> void combinationUtil(int arr[], int n, int r, int count, int data[], int i); // Needed for qsort. See http ://w...content-available-to-author-only...s.com/reference/cstdlib/qsort/ int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[r]; // Sort array to handle duplicates qsort (arr, n, sizeof(int), compare); // Print all combination using temprary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */ void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current cobination is ready, print it if (index == r) { for (int j=0; j<r; j++) printf("%d ",data[j]); printf("\n"); return; } // When no more elements are there to be put if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // Remove duplicates while (arr[i] == arr[i+1]) i++; // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // Driver program to test above functions int main() { int arr[] = {1, 2, 1, 3, 1}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0; }

Java

/*package whatever //do not write package name here */ import java.util.Arrays; public class CombinationGenerator { // The main function that prints all combinations of size r // in arr[] of size n. public static void main(String[] args) { int arr[] = {1, 2, 1, 3, 1}; int r = 3; int n = arr.length; printCombination(arr, n, r); } // A utility function to print an array static void printArray(int data[], int r) { for (int i = 0; i < r; i++) System.out.print(data[i] + " "); System.out.println(); } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[] = new int[r]; // Sort array to handle duplicates Arrays.sort(arr); // Print all combinations using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store the current combination i ---> Index of the current element in arr[] */ static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready, print it if (index == r) { printArray(data, r); return; } // When no more elements are there to be put if (i >= n) return; // Current element is included, put the next element at the next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // Remove duplicates while (i < n - 1 && arr[i] == arr[i + 1]) i++; // Current element is excluded, replace it with the next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i + 1); } } // This code is contributed by akshitaguprzj3

C#

using System; class Program { // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void PrintCombination(int[] arr, int n, int r) { // A temporary array to store all combinations one by one int[] data = new int[r]; // Sort array to handle duplicates Array.Sort(arr); // Print all combinations using temporary array 'data[]' CombinationUtil(arr, n, r, 0, data, 0); } /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of the current element in arr[] */ static void CombinationUtil(int[] arr, int n, int r, int index, int[] data, int i) { // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + " "); Console.WriteLine(); return; } // When no more elements are there to be put if (i >= n) return; // Current is included, put next at the next location data[index] = arr[i]; CombinationUtil(arr, n, r, index + 1, data, i + 1); // Remove duplicates while (i < n - 1 && arr[i] == arr[i + 1]) i++; // Current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) CombinationUtil(arr, n, r, index, data, i + 1); } // Driver program to test above functions static void Main() { int[] arr = { 1, 2, 1, 3, 1 }; int r = 3; int n = arr.Length; PrintCombination(arr, n, r); } }

JavaScript

// Program to print all combinations of size r in an array of size n // Function to perform combination utility function combinationUtil(arr, n, r, index, data, i) { // Current combination is ready, print it if (index === r) { console.log(data.join(' ')); return; } // When no more elements are there to be put if (i >= n) return; // Current element is included, put the next at the next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // Remove duplicates while (arr[i] === arr[i + 1]) i++; // Current element is excluded, replace it with the next // (Note that i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i + 1); } // Function to sort array needed for handling duplicates function compare(a, b) { return a - b; } // Main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() function printCombination(arr, n, r) { // A temporary array to store all combinations one by one let data = new Array(r); // Sort array to handle duplicates arr.sort(compare); // Print all combinations using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } // Driver program to test the above functions function main() { let arr = [1, 2, 1, 3, 1]; let r = 3; let n = arr.length; printCombination(arr, n, r); } // Execute the main function main(); // This code is contributed by akshitaguprzj3

Python3

from itertools import combinations # Function to print all combinations of size r in an array of size n def print_combination(arr, n, r): # Sort the array to handle duplicates arr.sort() # A temporary list to store combinations one by one data = [0] * r # Function to print all combinations using the temporary list 'data' def combination_util(index, i): # Current combination is ready, print it if index == r: for j in range(r): print(data[j], end=" ") print() return # When there are no more elements to be added if i >= n: return # Include the current element and move to the next location data[index] = arr[i] combination_util(index + 1, i + 1) # Skip duplicates while i < n - 1 and arr[i] == arr[i + 1]: i += 1 # Exclude the current element and move to the next (Note that i+1 is passed, but index is not changed) combination_util(index, i + 1) # Start the combination generation process combination_util(0, 0) # Driver program to test the function if __name__ == "__main__": arr = [1, 2, 1, 3, 1] r = 3 n = len(arr) print_combination(arr, n, r)


Output

1 1 1 1 1 2 1 1 3 1 2 3


 



Similar Reads

itertools.combinations() module in Python to print all possible combinations
Given an array of size n, generate and print all possible combinations of r elements in array. Examples: Input : arr[] = [1, 2, 3, 4], r = 2Output : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve th
2 min read
Print all combinations | Set-1
Given two numbers n and k, you have to print all possible combinations of k numbers from 1...n. Examples: Input : n = 4 k = 2 Output: 1 2 1 3 1 4 2 3 2 4 3 4 Input : n = 5 k = 3 Output : 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 Print all combinations using Backtracking:The idea is to use a recursive approach to construct these co
6 min read
Print all combinations of points that can compose a given number
You can win three kinds of basketball points, 1 point, 2 points, and 3 points. Given a total score of n, print out all the combinations to compose n. Examples: For n = 1, the program should print following: 1 For n = 2, the program should print following: 1 1 2 For n = 3, the program should print following: 1 1 1 1 2 2 1 3 For n = 4, the program sh
9 min read
Print all the combinations of a string in lexicographical order
Given a string str, print of all the combinations of a string in lexicographical order.Examples: Input: str = "ABC" Output: A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA Input: ED Output: D DE E ED Approach: Count the occurrences of all the characters in the string using a map, then using recursion all the possible combinations can be printed. St
9 min read
Print all possible combinations of the string by replacing '$' with any other digit from the string
Given a number as a string where some of the digits are replaced by a '$', the task is to generate all possible number by replacing the '$' with any of the digits from the given string.Examples: Input: str = "23$$" Output: 2322 2323 2332 2333Input: str = "$45" Output: 445 545 Approach: Find all the combinations of the string by replacing the charac
15+ min read
Print all combinations generated by characters of a numeric string which does not exceed N
Given a numeric string S of length M and an integer N, the task is to find all distinct combinations of S (repetitions allowed) that are at most N. Examples: Input: S = "124", N = 100Output: 1, 11, 12, 14, 2, 21, 22, 24, 4, 41, 42, 44Explanation: Combinations "111", "112", "122", "124", "412" are greater than 100. Therefore, these combinations are
7 min read
Print all unique combinations of setting N pieces on an NxN board
Given an integer N, the task is to print all the unique combinations of putting N pieces in an NxN board. Note: Print ("*") for pieces and ("-") for an empty space. Example: Input: N = 2Output:* *- - * -* - * -- * - ** - - *- * - -* *Explanation: The total number of empty spaces are 2*2=4 and the pieces to be set is 2 so there are 4C2 combinations
8 min read
Print all combinations of balanced parentheses
Given a number n, the task is to generate all possible n pairs of balanced parentheses. Examples: Input: n=1Output: {}Explanation: This the only sequence of balanced parenthesis formed using 1 pair of balanced parenthesis. Input : n=2Output: {}{} {{}}Explanation: This the only two sequences of balanced parenthesis formed using 2 pair of balanced pa
12 min read
Print all combinations of factors (Ways to factorize)
Write a program to print all the combinations of factors of given number n. Examples: Input : 16Output :2 2 2 2 2 2 4 2 8 4 4 Input : 12Output : 2 2 3 2 6 3 4To solve this problem we take one array of array of integers or list of list of integers to store all the factors combination possible for the given n. So, to achieve this we can have one recu
12 min read
Find all combinations of k-bit numbers with n bits set where 1 &lt;= n &lt;= k in sorted order
Given a number k, find all the possible combinations of k-bit numbers with n-bits set where 1 &lt;= n &lt;= k. The solution should print all numbers with one set bit first, followed by numbers with two bits set,.. up to the numbers whose all k-bits are set. If two numbers have the same number of set bits, then smaller number should come first. Exam
7 min read
Print combinations of distinct numbers which add up to give sum N
Given a positive integer N, the task is to find out all the combinations of positive integers that add upto the given integer N. The program should print only combinations, not permutations and all the integers in a combination must be distinct. For example, for input 3, either 1, 2 or 2, 1 should be printed and 1, 1, 1 must not be printed as the i
8 min read
Iterating over all possible combinations in an Array using Bits
There arise several situations while solving a problem where we need to iterate over all possible combinations of an array. In this article, we will discuss the method of using bits to do so.For the purpose of explaining, consider the following question: Given an array b[] = {2, 1, 4}. The task is to check if there exists any combination of element
7 min read
Find all combinations of two equal sum subsequences
Given an array arr[] of integers, the task is to find all possible ways the array could be split into two subsequences such that the sum of the elements in both the subsequences is equal. Each number in the array must belong to only one of the two subsequences. Print all possible combinations of two subsequences. Examples: Input: arr[] = {1, 2, 3,
11 min read
Generate all possible combinations of at most X characters from a given array
Given an array arr[] consisting of N characters, the task is to generate all possible combinations of at most X elements ( 1 ? X ? N). Examples: Input: N = 3, X = 2, arr[] = {'a', 'b', 'a'}Output: a b c bc ca ab cb ac baExplanation: All possible combinations using 1 character is 3 {'a', 'b', 'c'}. All possible combinations using 2 characters are {"
6 min read
Find all combinations of perfect squares that sum up to N with duplicates
Given a positive integer N, the task is to print all possible sum of perfect squares such that the total sum of all perfect squares is equal to N. Example: Input: N=8Output: 4 4 1 1 1 1 4 1 1 1 1 1 1 1 1 Explanation: There are three possible ways to make sum equal to N Input: N=3Output: 1 1 1 Approach: The given problem can be solved using recursio
7 min read
Count of all possible combinations of K numbers that sums to N
Given a number N, the task is to count the combinations of K numbers from 1 to N having a sum equal to N, with duplicates allowed. Example: Input: N = 7, K = 3Output:15Explanation:The combinations which lead to the sum N = 7 are: {1, 1, 5}, {1, 5, 1}, {5, 1, 1}, {2, 1, 4}, {1, 2, 4}, {1, 4, 2}, {2, 4, 1}, {4, 1, 2}, {4, 2, 1}, {3, 1, 3}, {1, 3, 3},
11 min read
Find all valid combinations of at most K numbers that sum up to N
Given two numbers N and K, the task is to find all valid combinations of at most K numbers that sum up to N such that the following conditions are true: Only numbers 1 through 9 are used.Each number is used at most once. Return a list of all possible valid combinations Examples: Input: K = 3, N = 7Output: 1 2 41 62 53 47 Input: K = 3, N = 9Output:
8 min read
Count of all valid combinations of at most K numbers that sum up to N
Given two numbers N and K, the task is to find the count of all valid combinations of at most K numbers that sum up to N such that the following conditions are true: Only numbers 1 through 9 are used.Each number is used at most once. Examples: Input: K = 3, N = 7Output: 5Explanation:1 2 41 62 53 47 Input: K = 3, N = 9Output: 8Explanation:1 2 61 3 5
7 min read
Generate all possible combinations of K numbers that sums to N
Given two integers N and K, the task is to find all valid combinations of K numbers that adds up to N based on the following conditions: Only numbers from the range [1, 9] used.Each number can only be used at most once.Examples: Input: N = 7, K = 3Output: 1 2 4Explanation: The only possible combination is of the numbers {1, 2, 4}. Input: N = 9, K =
9 min read
Find all combinations that add upto given number
Given a positive number, find out all combinations of positive numbers that adds upto that number. The program should print only combinations, not permutations. For example, for input 3, either 1, 2 or 2, 1 should be printed.Examples : Input: N = 3Output:1 1 11 23Input: N = 5Output:1 1 1 1 11 1 1 21 1 31 2 21 42 35 We strongly recommend you to mini
9 min read
All unique combinations whose sum equals to K (Combination Sum II)
Given an array arr[] of size N and an integer K. The task is to find all the unique combinations from the given array such that sum of the elements in each combination is equal to K. Examples: Input: arr[] = {1, 2, 3}, K = 3 Output: {1, 2} {3} Explanation:These are the combinations whose sum equals to 3. Input: arr[] = {2, 2, 2}, K = 4 Output: {2,
7 min read
All combinations of strings that can be used to dial a number
Given a number, print all possible combinations of strings that can be used to dial the given number in a phone with following specifications. In the given phone, we can dial, 2 using A or B or C, 3 using D or E or F, ................... 8 using T or U or V, 9 using W or X or Y or Z, 1 using only 1 0 using 0. For example if 23, is the given phone n
5 min read
Problem on permutations and combinations | Set 2
Prerequisite : Permutation and Combination Given a polygon of m sides, count number of triangles that can be formed using vertices of polygon. Answer : [m (m - 1)(m - 2) / 6] Explanation : There are m vertices in a polygon with m sides. We need to count different combinations of three points chosen from m. So answer is mC3 = m * (m - 1) * (m - 2) /
4 min read
K maximum sum combinations from two arrays
Given two equally sized arrays (A, B) and N (size of both arrays). A sum combination is made by adding one element from array A and another element of array B. Display the maximum K valid sum combinations from all the possible sum combinations. Examples: Input : A[] : {3, 2} B[] : {1, 4} K : 2 [Number of maximum sum combinations to be printed]Outpu
15 min read
Count possible combinations of pairs with adjacent elements from first N numbers
Given a number N, the task is to count all possible combinations of pairs formed using adjacent elements.Note: If an element exists already in a pair, it cannot be picked in the next pair. For example: for {1,2,3}: {1,2} and {2,3} will not be considered as a correct combination.Examples: Input : N = 4 Output : 5 Explanation : If N = 4, the possible
8 min read
Count valid Bitwise operation combinations for Binary Strings
Given an odd integer N (N &gt;= 3), a binary string S of length N and another string O of length (N-1)/2. Here, each character in string O can be one of the following: '&amp;', '|' or '^' representing Bitwise operations AND, OR, and XOR respectively, the task is to find the number of possible combinations for string O that satisfies the following c
8 min read
Combinations where every element appears twice and distance between appearances is equal to the value
Given a positive number n, we need to find all the combinations of 2*n elements such that every element from 1 to n appears exactly twice and distance between its appearances is exactly equal to value of the element. Examples: Input : n = 3 Output : 3 1 2 1 3 2 2 3 1 2 1 3 All elements from 1 to 3 appear twice and distance between two appearances i
7 min read
Combinations from n arrays picking one element from each array
Given a list of arrays, find all combinations where each combination contains one element from each given array. Examples: Input : [ [1, 2], [3, 4] ] Output : 1 3 1 4 2 3 2 4 Input : [ [1], [2, 3, 4], [5] ] Output : 1 2 5 1 3 5 1 4 5 We keep an array of size equal to the total no of arrays. This array called indices helps us keep track of the index
8 min read
CSES Solutions - Word Combinations
You are given a string S of length N and a dictionary arr[] containing K words. In how many ways can you create the string using the words? Examples: Input: S = "ababc", K = 4, arr[] = {ab, abab, c, cb}Output: 2Explanation: The possible ways are "ab" + "ab" + "c" and "abab" + "c". Input: S = "geeksforgeeks", K = 3, arr[] = {geeks, for, geeks}Output
10 min read
CSES Solutions - Coin Combinations I
Consider a money system consisting of N coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ways you can produce a money sum X using the available coins. Examples: Input: N = 3, X = 9, coins[] = {2, 3, 5}Output: 8Explanation: There are 8 number of ways to make sum = 9. {2, 2, 5} = 2 + 2 + 5 = 9{2, 5, 2} =
8 min read
Article Tags :
Practice Tags :