oneby7

Recursion and Backtracking Generating every choice

328. Combination Sum III

Medium

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

Output: [[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

Output: [[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

Output: []

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.

k = 2, target = 6

Constraints

  • 2 ≤ k ≤ 9
  • 1 ≤ target ≤ 60

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.