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.
|Replacements/Repetitions allowed||Replacements/Repetitions not allowed|
|Permutations/Order Important||nr possibilities
See the special case when r=n below
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 )
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.
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.
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 firstname.lastname@example.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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- itertools.combinations() module in Python to print all possible combinations
- Make all combinations of size k
- Problem on permutations and combinations | Set 2
- Print all the combinations of N elements by changing sign such that their sum is divisible by M
- Iterating over all possible combinations in an Array using Bits
- Iterative approach to print all combinations of an Array
- Combinations from n arrays picking one element from each array
- Combinations in a String of Digits
- Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
- Count numbers up to N which contains at least one repeated digit
- Count lexicographically increasing K-length strings possible from first N alphabets
- Count alphanumeric palindromes of length N
- Sum of all possible triplet products from given ranges
- Count pairs whose product contains single distinct prime factor