Combinations
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Backtracking.
Combinations
Choosing K from N
This is a classic problem. The goal is to choose elements from the set . Unlike permutations, the order doesn't matter.
Efficient Search
To avoid duplicate combinations like
[1, 2] and [2, 1], we always choose numbers in increasing order. This means after choosing , the next number must be from .Pruning Optimization
If the number of remaining elements in the set is less than the number of elements we still need to pick, we can backtrack early.
Choose K numbers from 1 to N. Includes visual increasing-order tree.
Examples
Input: n = 4, k = 2
Output: [[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
Approach 1
Level I: Recursive Backtracking (Include/Exclude)
Intuition
For each number from 1 to , we either include it in our current combination or skip it.
At index , we either add to our list and call
dfs(i + 1, count + 1), or we don't add and call dfs(i + 1, count). If count == k, we found a solution.⏱ O(k * C(N, k))💾 O(k) for recursion stack.
Detailed Dry Run
Dry Run: n=3, k=2
| Start | Path | Action | Next State |
| :---- | :--- | :----------------- | :--------- |
| 1 | [] | Choose 1, dfs(2) | [1] |
| 2 | [1] | Choose 2, RES:[1,2]| - |
| 2 | [1] | Backtrack, try 3 | [1,3] |
| 3 | [1] | Choose 3, RES:[1,3]| - |
| 1 | [] | Skip 1, try Choose 2| [2] |Approach 2
Level II: Optimized Backtracking (Loop-based Pruning)
Intuition
Instead of binary choice, use a loop to pick the next element. Only iterate through elements that could possibly complete a combination of size .
The current number can go up to . Beyond that, there aren't enough numbers left to reach size .
⏱ O(k * C(N, k))💾 O(k)
Detailed Dry Run
n=4, k=3
- At root, i can only go up to . So we only try picking 1 or 2 as the first element.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.