Problem Description
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. The answer can be returned in any order.
Key Insights
- The problem requires generating all unique combinations (order does not matter) from 1 to n.
- Backtracking (depth-first search) is ideal for exploring all possible combinations.
- We build combinations incrementally and backtrack when the current combination reaches a dead end or a complete combination of k numbers is formed.
- Pruning the recursion early by limiting the candidate range helps improve efficiency.
Space and Time Complexity
Time Complexity: O(k * C(n, k))
Space Complexity: O(k) for the recursion stack (not including space for the output)
Solution
We use a backtracking approach with depth-first search to generate all possible combinations. Start with an empty combination and recursively add numbers from a candidate range ensuring each new element is greater than the last added, which maintains the increasing order and avoids duplicates. When the length of the current combination equals k, add it to the result list. After exploring each path, backtrack by removing the last element and try the next number. The candidate range can be pruned since if the remaining numbers are insufficient to reach k, no further recursive calls are made.