Combinations

All k-combinations of [1..n] — DFS with start-index to avoid duplicates.

Medium
Time O(C(n, k) * k) Space O(k)
LeetCode
3 min read
backtracking combinations

Problem#

Return all k-element combinations of [1..n].

Examples#

  • n = 4, k = 2[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

Constraints#

  • 1 <= n <= 20, 1 <= k <= n.

Approach#

DFS with start index. At each level, pick a number ≥ start, recurse with start = picked + 1. Prune if remaining numbers can’t reach k.

Solution#

Combinations
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> out;
vector<int> path;
function<void(int)> dfs = [&](int start) {
if ((int)path.size() == k) { out.push_back(path); return; }
int need = k - path.size();
for (int i = start; i <= n - need + 1; ++i) {
path.push_back(i);
dfs(i + 1);
path.pop_back();
}
};
dfs(1);
return out;
}
};

Editorial#

The n - need + 1 upper bound prunes branches that can’t possibly fill k slots. Without it, the DFS still works but spends time exploring infeasible prefixes.

Complexity#

  • Time: O(C(n, k) * k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.