Practice LeetCode 77 · Combinations · GFG · nCr Combinations
RecursionBacktrackingCombinationsStart Index

Combinations · Choose k of n

Pick k elements where order doesn't matter. A start index enforces increasing picks so [1,2] and [2,1] aren't counted twice. Prune when too few elements remain to finish.

The start index

Recurse with a start value and only pick elements at index ≥ start. This forces every combination to be strictly increasing, killing the order-duplicates that plague permutations.

The "enough left" prune

  • Need k - path.size() more elements
  • Only n - i + 1 remain from index i
  • If remaining < needed → prune the branch
  • Record when path.size() == k

Choose k, in order

Unvisited Active Combination found Pruned
current path:
slowfast
Step 0
Nodes explored
0
Combinations
0
Expected C(n,k)
–
Pruned
0

C++

void dfs(int start, int n, int k,
         vector<int>& path, vector<vector<int>>& out) {
    if (path.size() == k) {          // picked enough
        out.push_back(path);
        return;
    }
    // prune: not enough numbers left to reach size k
    int need = k - path.size();
    for (int i = start; i <= n - need + 1; i++) {
        path.push_back(i);            // CHOOSE i
        dfs(i + 1, n, k, path, out);  // next starts after i
        path.pop_back();              // UNCHOOSE
    }
}

vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> out;
    vector<int> path;
    dfs(1, n, k, path, out);
    return out;                       // C(n, k) combinations
}
Time
O(C(n,k) · k)

One length-k copy per combination generated.

Space
O(k)

Recursion depth is capped at k, plus the working path.

Output
C(n,k)

n! / (k!·(n-k)!), order-independent selections.

  • Start index = no duplicates. Passing i+1 forward means each element can only be followed by larger ones, so sets never repeat in a different order.
  • The loop bound i <= n - need + 1 is the prune baked into the range, it never even enters doomed branches.
  • Combination Sum (LC 39) reuses the same start-index shape but allows reusing an element (pass i, not i+1).
  • Combinations vs permutations: order matters for permutations (n!), not for combinations (C(n,k)).
  • Record only at size k, intermediate prefixes are partial, not answers.