Combinations
Master this topic with zero to advance depth.
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
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.
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] |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 .
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.