Tensorum
LeetCode 77 · Combinations

Combinations

LeetCode 77 · Medium · solution, intuition & step-by-step walkthrough

Backtrack with a start index; stop at size k.

MediumBacktracking
105 msruntime · beats 76%
61.3 MBmemory · beats 82%
1approach
8accepted runs · last 2 Apr 2026

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. 1

    dfs(index, comb): size k → record.

  2. 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
Loading the step-through…

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.