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
- Write a program to reverse digits of a number
- Program to find whether a no is power of two
- Write an Efficient Method to Check if a Number is Multiple of 3
- Program to find parity
- Write an Efficient C Program to Reverse Bits of a Number
- Minimum number of jumps to reach end
- Print all combinations of balanced parentheses
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Print all combinations of points that can compose a given number
- Find Union and Intersection of two unsorted arrays
- Check if a number is multiple of 5 without using / and % operators
- To find sum of two numbers without using any operator
- Find day of the week for a given date
- Given a number, find the next smallest palindrome