Given a positive integer n, print all combinations of numbers between 1 and n having sum n.

For example,

For n = 5, the following combinations are possible:
 
{ 5 }
{ 1, 4 }
{ 2, 3 }
{ 1, 1, 3 }
{ 1, 2, 2 }
{ 1, 1, 1, 2 }
{ 1, 1, 1, 1, 1 }
 
 
For n = 4, the following combinations are possible:
 
{ 4 }
{ 1, 3 }
{ 2, 2 }
{ 1, 1, 2 }
{ 1, 1, 1, 1 }

Practice this problem

We can use recursion to solve this problem. The idea is to consider every integer i from 1 to n and add it to the output and recur for remaining elements [i…n] with reduced sum n-i. To avoid printing permutations, each combination will be constructed in non-decreasing order. If a combination with the given sum is reached, print it.

Following is the C, C++, Java, and Python implementation of the idea:

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

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).