Given a positive integer n and a target, find all combinations of distinct numbers in the interval [1,9] of length n that add up to the target.

For example,

Input: n = 4, target = 10
Output: [1, 2, 3, 4]
Explanation: The sum of all the elements in [1, 2, 3, 4] is 10. Only one combination is possible, since numbers cannot be repeated.
 
Input: n = 3, target = 3
Output: []
Explanation: The 3 smallest numbers between 1 and 9 are [1, 2, 3] and their sum is 6.
 
Input: n = 3, target = 12
Output:
[1, 2, 9]
[1, 3, 8]
[1, 4, 7]
[1, 5, 6]
[2, 3, 7]
[2, 4, 6]
[3, 4, 5]

We can use recursion to solve this problem. The idea is to consider every number i from 1 to 9 and recur for the remaining numbers [i+1…9] with the reduced sum target-i. To avoid printing permutations, we consider numbers in increasing order. If the combination size becomes n and the target is reached, keep track of it.

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

C++


Download  Run Code

Output:

1 2 9
1 3 8
1 4 7
1 5 6
2 3 7
2 4 6
3 4 5

Java


Download  Run Code

Output:

[[1, 2, 9], [1, 3, 8], [1, 4, 7], [1, 5, 6], [2, 3, 7], [2, 4, 6], [3, 4, 5]]

Python


Download  Run Code

Output:

[[1, 2, 9], [1, 3, 8], [1, 4, 7], [1, 5, 6], [2, 3, 7], [2, 4, 6], [3, 4, 5]]

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