combination-sum-iii.sh — zsh
backtrackingcombinatorics

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

  1. k = 3, n = 7 returns [[1,2,4]].
  2. k = 4, n = 1 returns [] because even the smallest 4 distinct digits sum to 10.
  3. k = 9, n = 45 returns [[1,2,3,4,5,6,7,8,9]].

Constraints

  • 1 <= k <= 9
  • 1 <= n <= 60
  • Use only digits 1..9
  • Every combination must contain exactly k distinct 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
Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2
Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Example 3
Input: k = 4, n = 1
Output: []