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 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
- Find minimum number of Log value needed to calculate Log upto N
- Find square root of number upto given precision using binary search
- Print all combinations of points that can compose a given number
- Find sum of the series ?3 + ?12 +......... upto N terms
- Find Sum of Series 1^2 - 2^2 + 3^2 - 4^2 ..... upto n terms
- Find the sum of series 3, -6, 12, -24 . . . upto N terms
- Find the sum of series 0.X + 0.XX + 0.XXX +... upto k terms
- Find the sum of the series 1+11+111+1111+..... upto n terms
- Find sum of the series 1+22+333+4444+...... upto n terms
- Program to find the sum of the series 23+ 45+ 75+..... upto N terms
- Program to count number of distinct Squares and Cubes upto N
- Print all combinations of balanced parentheses
- Print all combinations of factors (Ways to factorize)
- Print all possible combinations of r elements in a given array of size n
- Print combinations of distinct numbers which add up to give sum N