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.
Input: N = 3 Output: 1 1 1 1 2 3 Input: N = 5 Output: 1 1 1 1 1 1 1 1 2 1 1 3 1 2 2 1 4 2 3 5
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to use recursion. We use an array to store combinations and we recursively fill the array and recurse with reduced number. The invariant used in the solution is that each combination will always be stored in increasing order of elements involved. That way we can avoid printing permutations.
Below is implementation of above idea :
1 1 1 1 1 1 1 1 2 1 1 3 1 2 2 1 4 2 3 5
Exercise : Modify above solution to consider only distinct elements in a combination.
This article is contributed by Aditya Goel. 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.
- Print combinations of distinct numbers which add up to give sum N
- Print all combinations of points that can compose a given number
- Print all possible combinations of r elements in a given array of size n
- Find square root of number upto given precision using binary search
- Print all combinations of balanced parentheses
- Print all combinations of factors (Ways to factorize)
- Find N fractions that sum upto a given fraction N/D
- Find initial sequence that produces a given Array by cyclic increments upto index P
- Find minimum number of Log value needed to calculate Log upto N
- Sum of largest divisor of numbers upto N not divisible by given prime number P
- Sum of GCD of all numbers upto N with N itself
- Minimise N such that sum of count of all factors upto N is greater than or equal to X
- Sum of product of all integers upto N with their count of divisors
- Count of all values of N in [L, R] such that count of primes upto N is also prime
- Find the sum of the series 1+11+111+1111+..... upto n terms
- Find the sum of series 0.X + 0.XX + 0.XXX +... upto k terms
- Find sum of the series 1+22+333+4444+...... upto n terms
- Find sum of the series ?3 + ?12 +......... upto N terms
- Find the sum of series 3, -6, 12, -24 . . . upto N terms
- Program to find the sum of the series 23+ 45+ 75+..... upto N terms