Combinations

Medium#77combinations

You get two numbers, n and k. Return every way to choose k different numbers from 1 to n, where order does not matter: [1, 2] and [2, 1] are the same choice. Our example: n = 4, k = 3 gives 4 choices, [1, 2, 3], [1, 2, 4], [1, 3, 4] and [2, 3, 4].

input
n and k: integers.
returns
Every combination of k different numbers from 1 to n, each one once. Combinations in any order, numbers in a combination too.
constraints
  • 1 ≤ n ≤ 12
  • 1 ≤ k ≤ n
our 10 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} n
 * @param {number} k
 * @return {number[][]}
 */
function combine(n, k) {

}
Ctrl ↵
format
reset

saved in this browser

10 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more backtracking problems

Pattern “Backtracking” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.