Combinations
LeetCode 77 · Medium · solution, intuition & step-by-step walkthrough
Backtrack with a start index; stop at size k.
This is how I solved Combinations (LeetCode 77), a medium problem from the Combinations pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Build combinations in increasing order: pick a number, then only consider larger numbers next. When the combination reaches size k, record it.
Approach
- 1
dfs(index, comb): size k → record.
- 2
For i from index to n: append, recurse with i+1, pop.
How I solved it
BacktrackingPythonO(k·C(n,k)) time
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res=[]
def dfs(index,comb):
if len(comb)==k:
res.append(comb[:])
return
for i in range(index,n+1):
comb.append(i)
dfs(i+1,comb)
comb.pop()
dfs(1,[])
return res
Combinations — FAQ
What is the intuition behind Combinations?
Build combinations in increasing order: pick a number, then only consider larger numbers next. When the combination reaches size k, record it.
How do you solve Combinations (LeetCode 77)?
1. dfs(index, comb): size k → record. 2. For i from index to n: append, recurse with i+1, pop.
What is the time and space complexity of Combinations?
Time: O(k · C(n, k)). Space: O(k). (Accepted approach: Backtracking.)
What are common mistakes in Combinations?
Pruning when not enough numbers remain (n − i + 1 < k − len) speeds it up.