MEDIUM Backtracking

77. Combinations

๐Ÿ“– Problem

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

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขRecursive function frames
  • โ€ขPush/pop state undo
  • โ€ขPruning branches early

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Backtracking reasoning pattern
  • โ€ขApply Recursion reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use backtracking to generate all combinations
  • โ†’ Start from each number and recursively build combinations
  • โ†’ Avoid duplicates by only moving forward in array
  • โ†’ When combination reaches size k, save it
  • โ†’ Time: O(C(n,k)), Space: O(C(n,k)) for results

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse backtracking to generate all combinations
  • โ€ขStart from each number and recursively build combinations
  • โ€ขAvoid duplicates by only moving forward in array

Common Pitfalls

  • โ€ขWhen combination reaches size k, save it
  • โ€ขTime: O(C(n,k)), Space: O(C(n,k)) for results

๐Ÿงช Test Cases

Test Case 1
Not run
Input:
combine(4, 2);
Expected:
[[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
Test Case 2
Not run
Input:
combine(1, 1);
Expected:
[[1]]
Test Case 3
Not run
Input:
combine(n: number, k: number);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit