oneby7

Recursion and Backtracking Generating every choice

326. Combinations

Medium

You are given two integers n and k. Return every combination of k different numbers chosen from the numbers 1 to n.

A combination is a choice of numbers in which order does not matter, so [1,3] and [3,1] are the same combination and you return it once. A combination never uses the same number twice.

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: n = 5, k = 3

Output: [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,3,5], [1,4,5], [2,3,4], [2,3,5], [2,4,5], [3,4,5]]

Explanation: There are ten ways to choose three of the numbers 1 to 5. Six of them use 1, three more use 2 but not 1, and [3,4,5] uses neither.

Example 2

Input: n = 4, k = 1

Output: [[1],[2],[3],[4]]

Explanation: With one number to choose, each number from 1 to 4 is a combination on its own.

Example 3

Input: n = 3, k = 3

Output: [[1,2,3]]

Explanation: When k equals n, the only combination takes every number.

Check your understanding

Work out the answer for this input before you write any code.

n = 3, k = 2

Constraints

  • 1 ≤ k ≤ n ≤ 20

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.