Print all combinations of positive integers in increasing order that sum to a given number

Write code to print all combinations of positive integers in increasing order that sum to a given positive number.


 

For example,


Input: N = 3

1 1 1
1 2
3

Input: N = 4

1 1 1 1
1 1 2
1 3
2 2
4

Input: N = 5

1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5

 
The problem can be easily solved using recursion by taking help of an auxiliary array to store combinations. This approach is shown below in C and Java:

C

Download   Run Code



1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5

Java

Download   Run Code

Output:

1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5

 
Author: Aditya Goel

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of