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.
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++ 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
start & end ---> Starting and Ending indexes in arr
CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1);
// Driver program to test above functions
vararr = [1, 2, 3, 4];
varn = arr.length;
varr = 2;
CombinationRepetition(arr, n, r);
// This code is contributed by shikhasingrajput
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/Combination This 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 email@example.com. 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
Please Login to comment...