Combination Sum III
Given two integers k and n, return every valid combination of exactly k distinct digits chosen from 1 through 9 whose sum is n. Each digit may be used at most once in a combination.
For this question, keep the output deterministic: each combination must list its digits in increasing order, and the outer list must follow the natural depth-first search order created by trying candidate digits 1 through 9 in increasing order at every backtracking step. When a partial combination reaches length k and sum n, record it immediately; that DFS discovery order is the required output order.
Input / output
- Input:
k: int,n: int - Output:
int[][]in canonical DFS order
More examples
k = 3, n = 7returns[[1,2,4]].k = 4, n = 1returns[]because even the smallest 4 distinct digits sum to10.k = 9, n = 45returns[[1,2,3,4,5,6,7,8,9]].
Constraints
1 <= k <= 91 <= n <= 60- Use only digits
1..9 - Every combination must contain exactly
kdistinct digits
Follow-up
How can you prune the backtracking tree early by proving that the remaining slots are too small or too large to ever reach the target sum?
Examples
Example 1
Example 2
Example 3