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
๐งญ Prerequisites
๐ ๏ธ 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
๐ค Output