Open In App

Combinations with repetitions

Last Updated : 23 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 Combinatorics
1) 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

  Replacements/Repetitions allowed Replacements/Repetitions not allowed
Permutations/Order Important nr possibilities 
https://www.geeksforgeeks.org/print-all-combinations-of-given-length/
See the special case when r=n below
https://www.geeksforgeeks.org/print-all-permutations-with-repetition-of-characters
nPr possibilities 
https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ 
Here r=n, as we are permuting all the characters of the string.
Combinations/Order Not Important n+r-1Cr possibilities
Current Article ( https://www.geeksforgeeks.org/combinations-with-repetitions )
nCr possibilities
https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/

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
 

Comb

Below is the implementation. 

C++




// 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 functions
int 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




// 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 functions
int main()
{
    int arr[] = {1, 2, 3, 4};
    int n = sizeof(arr)/sizeof(arr[0]);
    int r = 2;
    CombinationRepetition(arr, n, r);
    return 0;
}


Java




// Java program to print all combination of size r in an array
// of size n with repetitions allowed
 
class GFG {
 
    /* 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 */
    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




# 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 code
arr = [ 1, 2, 3, 4 ]
r = 2
n = len(arr) - 1
 
CombinationRepetition(arr, n, r)
 
# This code is contributed by Vaibhav Kumar 12.


C#




// 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 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 */
    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


Javascript




<script>
// javascript program to print all combination of size r in an array
// of size n with repetitions allowed
   /* 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 */
    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 functions
var 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.
Referenceshttps://en.wikipedia.org/wiki/Combination

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads