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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of