Combinations Medium 0 attempts
LeetCode ↗

Combinations

Medium BacktrackingRecursion LeetCode

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. The answer can be in any order.

Each combination is a unique selection — [1, 2] and [2, 1] are the same combination, so only one should appear.

Examples

Input: n = 4, k = 2
Output: [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
Input: n = 1, k = 1
Output: [[1]]

Constraints

  • 1 <= n <= 20
  • 1 <= k <= n
Sample Input
n = 4, k = 2
Sample Output
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Constraints
  • 1 <= n <= 20
  • 1 <= k <= n
Test Cases
Case 1
Args: [4,2] Expected: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

Backtrack through choices starting from 1. At each step, pick a number greater than the last chosen one and recurse with k - 1. When k reaches 0, save the current combination. An optimization: stop early if there aren't enough numbers left to fill the remaining slots.

function combine(n, k) {
  const result = [];

  function backtrack(start, current) {
    if (current.length === k) {
      result.push([...current]);
      return;
    }
    const remaining = k - current.length;
    for (let i = start; i <= n - remaining + 1; i++) {
      current.push(i);
      backtrack(i + 1, current);
      current.pop();
    }
  }

  backtrack(1, []);
  return result;
}

Time: O(C(n, k) * k) — there are C(n, k) combinations, each taking O(k) to copy. Space: O(k) for the recursion stack.

Saved in this browser only. Private to you.

JavaScript