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

Practice this problem

We can easily solve the problem using recursion by taking the help of an auxiliary array to store combinations. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

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]

Python


Download  Run Code

Output:

[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).

 
Author: Aditya Goel