We are asked to generate all combinations of k numbers out of 1 ... n.
Constraints:
1 <= n <= 201 <= k <= n
Key insights:
- This is a classic backtracking / DFS problem.
- We build combinations incrementally and explore all possibilities.
- To avoid duplicates: always consider numbers greater than the last chosen.
- Initialize an empty
pathto store the current combination. - Start recursion (
backtr) fromcurr = 1up ton:- Append
itopath. - Recurse with
i + 1as the next starting point. - Backtrack by removing the last element after recursion.
- Append
- Stop recursion when
path.size() == kand pushpathinto the result.
- Use backtracking: choose → recurse → undo choice.
- To avoid duplicates, always move forward in the number range (
i + 1). - Use
path.reserve(k)for efficiency if needed (preallocate memory). - Simple recursion is enough; no need for extra visited array.
- Time:
O(C(n, k) * k)C(n, k)is the number of combinations.- Each combination costs
O(k)to copy into the result.
- Space:
O(k)for recursion stack and current path.