Recursion and Backtracking Generating every choice
328. Combination Sum III
You are given two integers k and target. Return every combination of exactly k different numbers
from 1 to 9 that add up to target. Each number from 1 to 9 can be used at most once in a combination.
A combination is a set of numbers, so [1,2,9] and [9,1,2] are the same combination and you return it
once. If no combination adds up to target, return an empty list.
The combinations can come back in any order, and so can the numbers inside each one. Any order is accepted. The examples list each combination's numbers from smallest to largest and sort the combinations.
Example 1
Input: k = 3, target = 12
[[1,2,9],
[1,3,8],
[1,4,7],
[1,5,6],
[2,3,7],
[2,4,6],
[3,4,5]]Explanation: Seven sets of three different numbers add up to 12. [4,4,4] and [2,5,5] also add up to 12, but they
use a number twice, so they do not count.
Example 2
Input: k = 2, target = 17
[[8,9]]Explanation: Only 8 + 9 gives 17. 7 + 10 would too, but the numbers stop at 9.
Example 3
Input: k = 4, target = 8
[]Explanation: The smallest four different numbers are 1, 2, 3 and 4, which already add up to 10. No set of four can reach a smaller target, so the answer is an empty list.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
2 ≤ k ≤ 91 ≤ target ≤ 60
Clarifying questions
What you would ask an interviewer before writing any code.