Combinations with repetitions - GeeksforGeeks

23 Jan, 2022
Suppose we have a string of length- n and we want to generate all combinations/permutations taken r at a time with/without repetitions.  There are four fundamental concepts in Combinatorics1) Combinations without repetitions/replacements. 2) Combinations with repetitions/replacements. 3) Permutations without repetitions/replacements. 4) Permutations with repetitions/replacements.Below is a summary table depicting the fundamental concepts in Combinatorics Theory.  
Summary Table
This article is about the third case(Order Not important and Repetitions allowed).The idea is to recur for all the possibilities of the string, even if the characters are repeating.The base case of the recursion is when there is a total of ‘r’ characters and the combination is ready to be printed. For clarity, see the recursion tree for the string- “ 1 2 3 4” and r=2 
Below is the implementation. 
C++
C
Java
Python3
C#
Javascript
// C++ program to print all combination of size r in an array// of size n with repetitions allowed#include <bits/stdc++.h>using namespace std; /* arr[]  ---> Input Array  chosen[] ---> Temporary array to store indices of                   current combination   start & end ---> Starting and Ending indexes in arr[]   r ---> Size of a combination to be printed */void CombinationRepetitionUtil(int chosen[], int arr[],                    int index, int r, int start, int end){    // Since index has become r, current combination is    // ready to be printed, print    if (index == r)    {        for (int i = 0; i < r; i++)            cout<<" "<< arr[chosen[i]];        cout<<"\n";        return;    }     // One by one choose all elements (without considering    // the fact whether element is already chosen or not)    // and recur    for (int i = start; i <= end; i++)    {        chosen[index] = i;        CombinationRepetitionUtil(chosen, arr, index + 1,                                               r, i, end);    }    return;} // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()void CombinationRepetition(int arr[], int n, int r){    // Allocate memory    int chosen[r+1];     // Call the recursive function    CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);} // Driver program to test above functionsint main(){    int arr[] = {1, 2, 3, 4};    int n = sizeof(arr)/sizeof(arr[0]);    int r = 2;    CombinationRepetition(arr, n, r);    return 0;}// this code is contributed by shivanisinghss2110
// C program to print all combination of size r in an array// of size n with repetitions allowed#include <stdio.h> /* arr[]  ---> Input Array  chosen[] ---> Temporary array to store indices of                   current combination   start & end ---> Starting and Ending indexes in arr[]   r ---> Size of a combination to be printed */void CombinationRepetitionUtil(int chosen[], int arr[],                    int index, int r, int start, int end){    // Since index has become r, current combination is    // ready to be printed, print    if (index == r)    {        for (int i = 0; i < r; i++)            printf("%d ", arr[chosen[i]]);        printf("\n");        return;    }     // One by one choose all elements (without considering    // the fact whether element is already chosen or not)    // and recur    for (int i = start; i <= end; i++)    {        chosen[index] = i;        CombinationRepetitionUtil(chosen, arr, index + 1,                                               r, i, end);    }    return;} // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()void CombinationRepetition(int arr[], int n, int r){    // Allocate memory    int chosen[r+1];     // Call the recursive function    CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);} // Driver program to test above functionsint main(){    int arr[] = {1, 2, 3, 4};    int n = sizeof(arr)/sizeof(arr[0]);    int r = 2;    CombinationRepetition(arr, n, r);    return 0;}
// Java program to print all combination of size r in an array// of size n with repetitions allowed class GFG {     /* arr[] ---> Input Arraychosen[] ---> Temporary array to store indices of                current combinationstart & end ---> Starting and Ending indexes in arr[]r ---> Size of a combination to be printed */    static void CombinationRepetitionUtil(int chosen[], int arr[],            int index, int r, int start, int end) {        // Since index has become r, current combination is        // ready to be printed, print        if (index == r) {            for (int i = 0; i < r; i++) {                System.out.printf("%d ", arr[chosen[i]]);            }            System.out.printf("\n");            return;        }         // One by one choose all elements (without considering        // the fact whether element is already chosen or not)        // and recur        for (int i = start; i <= end; i++) {            chosen[index] = i;            CombinationRepetitionUtil(chosen, arr, index + 1,                    r, i, end);        }        return;    } // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()    static void CombinationRepetition(int arr[], int n, int r) {        // Allocate memory        int chosen[] = new int[r + 1];         // Call the recursive function        CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1);    } // Driver program to test above functions    public static void main(String[] args) {        int arr[] = {1, 2, 3, 4};        int n = arr.length;        int r = 2;        CombinationRepetition(arr, n, r);    }} /* This Java code is contributed by PrinciRaj1992*/
# Python3 program to print all combination# of size r in an array of size n ''' arr[] ---> Input Array    chosen[] ---> Temporary array to store               current combination    start & end ---> Starting and Ending indexes in arr[]    r---> Size of a combination to be printed     '''def CombinationRepetitionUtil(chosen, arr, index,                              r, start, end):                                       # Current combination is ready,    # print it    if index == r:        for j in range(r):            print(chosen[j], end = " ")                     print()        return             # When no more elements are    # there to put in chosen[]    if start > n:        return             # Current is included, put    # next at next location    chosen[index] = arr[start]         # Current is excluded, replace it    # with next (Note that i+1 is passed,    # but index is not changed)    CombinationRepetitionUtil(chosen, arr, index + 1,                              r, start, end)    CombinationRepetitionUtil(chosen, arr, index,                              r, start + 1, end) # The main function that prints all# combinations of size r in arr[] of# size n. This function mainly uses# CombinationRepetitionUtil()def CombinationRepetition(arr, n, r):         # A temporary array to store    # all combination one by one    chosen = [0] * r     # Print all combination using    # temporary array 'chosen[]'    CombinationRepetitionUtil(chosen, arr, 0, r, 0, n) # Driver codearr = [ 1, 2, 3, 4 ]r = 2n = len(arr) - 1 CombinationRepetition(arr, n, r) # This code is contributed by Vaibhav Kumar 12.
// C# program to print all combination of size r in an array// of size n with repetitions allowed using System;public class GFG{      /* arr[] ---> Input Arraychosen[] ---> Temporary array to store indices of                current combinationstart & end ---> Starting and Ending indexes in arr[]r ---> Size of a combination to be printed */    static void CombinationRepetitionUtil(int []chosen, int []arr,            int index, int r, int start, int end) {        // Since index has become r, current combination is        // ready to be printed, print        if (index == r) {            for (int i = 0; i < r; i++) {                Console.Write(arr[chosen[i]]+" ");            }            Console.WriteLine();            return;        }         // One by one choose all elements (without considering        // the fact whether element is already chosen or not)        // and recur        for (int i = start; i <= end; i++) {            chosen[index] = i;            CombinationRepetitionUtil(chosen, arr, index + 1,                    r, i, end);        }        return;    } // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()    static void CombinationRepetition(int []arr, int n, int r) {        // Allocate memory        int []chosen = new int[r + 1];         // Call the recursive function        CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1);    } // Driver program to test above functions    public static void Main() {        int []arr = {1, 2, 3, 4};        int n = arr.Length;        int r = 2;        CombinationRepetition(arr, n, r);    }} // This code is contributed by PrinciRaj1992
<script>// javascript program to print all combination of size r in an array// of size n with repetitions allowed   /* arr ---> Input Arraychosen ---> Temporary array to store indices of                current combinationstart & end ---> Starting and Ending indexes in arrr ---> Size of a combination to be printed */    function CombinationRepetitionUtil(chosen , arr,            index , r , start , end)    {             // Since index has become r, current combination is        // ready to be printed, print        if (index == r) {            for (var i = 0; i < r; i++) {                document.write(arr[chosen[i]]+" ");            }            document.write("<br>");            return;        }         // One by one choose all elements (without considering        // the fact whether element is already chosen or not)        // and recur        for (var i = start; i <= end; i++) {            chosen[index] = i;            CombinationRepetitionUtil(chosen, arr, index + 1,                    r, i, end);        }        return;    } // The main function that prints all combinations of size r// in arr of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()    function CombinationRepetition(arr , n , r)    {             // Allocate memory        var chosen = Array.from({length: (r + 1)}, (_, i) => 0);         // Call the recursive function        CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1);    } // Driver program to test above functionsvar arr = [1, 2, 3, 4];var n = arr.length;var r = 2;CombinationRepetition(arr, n, r); // This code is contributed by shikhasingrajput</script>
Output : 
1 1 
1 2 
1 3 
1 4 
2 2 
2 3 
2 4 
3 3 
3 4 
4 4
Time Complexity:  For a string of length- n and combinations taken r at a time with repetitions, it takes a total of O(n+r-1Cr) time.References– https://en.wikipedia.org/wiki/CombinationThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
princiraj1992
Vaibhav Kumar 12
simmytarika5
shivanisinghss2110
khushboogoyal499
surindertarika1234
shikhasingrajput
simranarora5sos
Combinatorial
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Largest number by rearranging digits of a given positive or negative number
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Given number of matches played, find number of teams in tournament
Generate all possible combinations of at most X characters from a given array
Number of Simple Graph with N Vertices and M Edges
Largest substring with same Characters
Minimum cost to convert 1 to N by multiplying X or right rotation of digits
Print all Strong numbers less than or equal to N
Print all permutations with repetition of characters
Combinations from n arrays picking one element from each array