15% off all plans & roadmaps Use code
See plansCombinations
- LeetCode 77
- Medium
- Backtracking Patterns
- Subsets (Include/Exclude)
Updated
TL;DR: You must list every group of k numbers from 1 to n, where order inside a group does not matter. Build each group one number at a time, and cut off any branch that can no longer reach size k.
Problem
You get two integers, n and k. List every group of k distinct numbers chosen from the values 1 through n. Two groups hold the same numbers only when they match, so order inside a group does not matter. Return the groups in any order.
Example 1
Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Explanation: Picking 2 numbers out of 4 gives 6 groups. The group [2,1] is the same as [1,2], so it appears only once.
Example 2
Input: n = 1, k = 1 Output: [[1]] Explanation: Picking 1 number out of 1 gives one group.
Constraints
1 <= n <= 201 <= k <= n
Constraints that matter
- n up to 20 makes 2^n about one million, which is fast enough to enumerate, but most of those subsets have the wrong size.
- The answer can hold C(20, 10) = 184,756 lists, so the output size sets the floor for any correct method.
- k of at least 1 means the empty group is never an answer, so a size check can serve as the base case.
- k at most n guarantees that at least one group exists, so the search always has something to find.
Hints
Hint 1
The answer is a list of groups, and each group is a set of numbers.
Hint 2
Treat every subset of 1 through n as a candidate.
Solution
Intuition
The answer is a list of groups, and each group is a set of numbers. Treat every number from 1 to n as a yes or no decision: take it into the current group, or leave it out. That is the subsets (include/exclude) pattern. Backtracking walks those choices, and it undoes each one before trying the next.
Picture a row of people you walk past once, left to right, choosing whether each one joins a team of k. The team sheet is the current list, and erasing the last name is the undo step before you try leaving that person out.
Order is the trap. If each step could pick any unused number, the search would produce both [1,2] and [2,1]. Walking the numbers in increasing order fixes that. Every group then has exactly one path, which takes its smallest number first.
Pruning keeps the search small. Once a group holds k numbers, you record it and stop. If the numbers still ahead cannot fill the missing slots, you cut that branch. Those two checks mean every node you visit still leads to at least one answer.
Worked example
Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Explanation: Each group picks two of the four numbers. Groups are written in increasing order, so [2,1] never appears next to [1,2]. The six groups are every pair you can form from 1 to 4.
Approach 1: Brute force over all bitmasks
Treat every subset of 1 through n as a candidate. There are 2^n subsets, and a bitmask can encode each one, with bit i meaning number i + 1 is present. Keep only the masks that have exactly k bits set.
This is correct, but it builds subsets of every size. For n = 20 and k = 2, only 190 of the 1,048,576 masks survive the filter.
Steps
- Loop mask from 0 to 2^n - 1.
- Count the set bits in mask.
- If the count is not k, skip this mask.
- Read the bits. Bit i set means number i + 1 belongs to the group.
- Append that group to the result.
- Return the result.
Dry run
Masks 0 through 15 cover every subset of {1, 2, 3, 4}. Only masks with exactly two set bits pass the filter.
- Mask 3 (binary 0011) gives [1,2].
- Mask 5 (binary 0101) gives [1,3].
- Mask 6 (binary 0110) gives [2,3].
- Mask 9 (binary 1001) gives [1,4].
- Mask 10 (binary 1010) gives [2,4].
- Mask 12 (binary 1100) gives [3,4].
The six groups match the expected output, although the order differs.
Complexity
| Time | O(n * 2^n) |
|---|---|
| Space | O(n) extra, plus the output |
Let n be the range size. The loop runs 2^n times, and each pass checks up to n bits to build a group, so the work is O(n * 2^n). The output holds C(n, k) groups of length k, which is at most n * 2^n, so storing the answer does not change the bound. Beyond the output, the code keeps one group of length at most n.
PythonTested in our runner
from typing import List, Optional
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
# every mask from 0 to 2^n - 1 is one subset of 1..n
for mask in range(1 << n):
# keep only subsets of size k
if bin(mask).count('1') != k:
continue
# bit i set means number i + 1 is in the subset
combo = [i + 1 for i in range(n) if (mask >> i) & 1]
result.append(combo)
# masks are not visited in lexicographic order, so sort the groups
result.sort()
return result
C++Tested in our runner
using namespace std;
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
// Enumerate masks in lexicographic order of their member lists
// by iterating over the reversed bit ordering so output is sorted.
for (int mask = 0; mask < (1 << n); mask++) {
if (__builtin_popcount(mask) != k) {
continue;
}
vector<int> combo;
for (int i = 0; i < n; i++) {
if ((mask >> i) & 1) {
combo.push_back(i + 1);
}
}
result.push_back(combo);
}
// Sort lexicographically to match the expected ordering.
sort(result.begin(), result.end());
return result;
}
};JavaScriptTested in our runner
var combine = function(n, k) {
const result = [];
// Iterate over masks in lexicographic order of combinations via a sorted approach
// Build all masks with exactly k bits, then sort the results lexicographically
for (let mask = 0; mask < (1 << n); mask++) {
let bits = 0;
for (let m = mask; m > 0; m >>= 1) {
bits += m & 1;
}
if (bits !== k) {
continue;
}
const combo = [];
for (let i = 0; i < n; i++) {
if ((mask >> i) & 1) {
combo.push(i + 1);
}
}
result.push(combo);
}
// Sort lexicographically to match the expected order
result.sort((a, b) => {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return a[i] - b[i];
}
return 0;
});
return result;
};GoTested in our runner
func combine(n int, k int) [][]int {
result := [][]int{}
// Number j maps to bit n-j, so descending mask order yields lexicographic combinations.
for mask := (1 << n) - 1; mask >= 0; mask-- {
bits := 0
for m := mask; m > 0; m >>= 1 {
bits += m & 1
}
if bits != k {
continue
}
combo := []int{}
for j := 1; j <= n; j++ {
if (mask>>(n-j))&1 == 1 {
combo = append(combo, j)
}
}
result = append(result, combo)
}
return result
}The Subsets (Include/Exclude) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Subsets (Include/Exclude)
Part of Backtracking Patterns
Approach 2: Include/exclude backtracking with pruningOptimalSubsets (Include/Exclude)
What is slow in the bitmask version: it builds every subset, then throws away most of them, and it keeps enumerating past the point where a group already has k numbers. The insight that fixes it: grow one group as you go, decide each number in increasing order, stop at size k, and skip any exclude branch that cannot fill the missing slots.
At index i you choose either to include i, which appends it and recurses, or to exclude i, which only recurses. Before excluding, check that the n - i numbers after i can still supply k - size values. If they cannot, the branch is dead, and you skip it.
Why it is correct. Each group of k numbers has exactly one path, because numbers are only added in increasing order, so no group is produced twice and none is missed. A skipped exclude branch only happens when the numbers left cannot fill the missing slots, so that branch holds no valid group. So every group stays reachable at every step, and the search returns all of them and only them.
Steps
- Start with index 1 and an empty current list.
- If current has k numbers, copy it into the result and return.
- If index is greater than n, return.
- Append index to current and recurse on index + 1.
- Remove the last number from current to undo the include.
- If n - index is at least k - len(current), recurse on index + 1 without index. Otherwise skip this branch.
Dry run
Each row is one call. The current column shows the list before the action runs.
| Step | Call index | current before action | Action |
|---|---|---|---|
| 1 | 1 | [] | include 1 |
| 2 | 2 | [1] | include 2, size is 2, record [1,2] |
| 3 | 2 | [1] | undo, check 2 >= 1 passes, exclude 2 |
| 4 | 3 | [1] | include 3, record [1,3] |
| 5 | 3 | [1] | undo, check 1 >= 1 passes, exclude 3 |
| 6 | 4 | [1] | include 4, record [1,4] |
| 7 | 4 | [1] | undo, check 0 >= 1 fails, prune |
| 8 | 1 | [] | undo, check 3 >= 2 passes, exclude 1 |
| 9 | 2 | [] | include 2 |
| 10 | 3 | [2] | include 3, record [2,3] |
| 11 | 3 | [2] | undo, check 1 >= 1 passes, exclude 3 |
| 12 | 4 | [2] | include 4, record [2,4] |
| 13 | 4 | [2] | undo, check 0 >= 1 fails, prune |
| 14 | 2 | [] | undo, check 2 >= 2 passes, exclude 2 |
| 15 | 3 | [] | include 3 |
| 16 | 4 | [3] | include 4, record [3,4] |
| 17 | 4 | [3] | undo, check 0 >= 1 fails, prune |
| 18 | 3 | [] | undo, check 1 >= 2 fails, prune |
The recorded groups are [1,2], [1,3], [1,4], [2,3], [2,4], [3,4]. That matches the example output. Rows 7, 13, 17 and 18 show the pruning check cutting dead branches.
Complexity
| Time | O(n * C(n, k)) |
|---|---|
| Space | O(n) |
Let n be the range size, and let C(n, k) be the number of answers. Each call either records a group or branches on a number. The pruning check guarantees that every visited call still has a valid completion, so each call lies on a path from the root to one of the C(n, k) answers.
A path has at most n + 1 calls, which gives at most (n + 1) * C(n, k) calls. Each call does constant work apart from the copy at a leaf, which costs O(k) and stays inside the same bound. The recursion depth is at most n + 1, and the current list never holds more than k values, so extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
current = []
def backtrack(index: int) -> None:
# a full combination is recorded as a copy
if len(current) == k:
result.append(current[:])
return
if index > n:
return
# include index
current.append(index)
backtrack(index + 1)
current.pop()
# exclude index only if enough numbers remain after it
if n - index >= k - len(current):
backtrack(index + 1)
backtrack(1)
return resultJavaTested in our runner
import java.util.*;
class Solution {
private List<int[]> result;
private int[] current;
private int size;
private int n;
private int k;
public int[][] combine(int n, int k) {
this.n = n;
this.k = k;
result = new ArrayList<>();
current = new int[k];
size = 0;
backtrack(1);
return result.toArray(new int[0][]);
}
private void backtrack(int index) {
if (size == k) {
result.add(current.clone()); // copy the array
return;
}
if (index > n) {
return;
}
// include index
current[size++] = index;
backtrack(index + 1);
size--;
// exclude index only if enough numbers remain after it
if (n - index >= k - size) {
backtrack(index + 1);
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
vector<int> current;
backtrack(1, n, k, current, result);
return result;
}
private:
void backtrack(int index, int n, int k, vector<int>& current, vector<vector<int>>& result) {
if ((int)current.size() == k) {
result.push_back(current); // push_back copies the vector
return;
}
if (index > n) {
return;
}
current.push_back(index);
backtrack(index + 1, n, k, current, result);
current.pop_back();
if (n - index >= k - (int)current.size()) {
backtrack(index + 1, n, k, current, result);
}
}
};JavaScriptTested in our runner
var combine = function(n, k) {
const result = [];
const current = [];
const backtrack = (index) => {
if (current.length === k) {
result.push(current.slice());
return;
}
if (index > n) {
return;
}
current.push(index);
backtrack(index + 1);
current.pop();
if (n - index >= k - current.length) {
backtrack(index + 1);
}
};
backtrack(1);
return result;
};GoTested in our runner
func combine(n int, k int) [][]int {
result := [][]int{}
current := []int{}
var backtrack func(index int)
backtrack = func(index int) {
if len(current) == k {
combo := make([]int, len(current))
copy(combo, current)
result = append(result, combo)
return
}
if index > n {
return
}
current = append(current, index)
backtrack(index + 1)
current = current[:len(current)-1]
if n-index >= k-len(current) {
backtrack(index + 1)
}
}
backtrack(1)
return result
}C#Tested in our runner
public class Solution {
private List<int[]> result;
private int[] current;
private int size;
private int n;
private int k;
public int[][] combine(int n, int k) {
this.n = n;
this.k = k;
result = new List<int[]>();
current = new int[k];
size = 0;
Backtrack(1);
return result.ToArray();
}
private void Backtrack(int index) {
if (size == k) {
result.Add((int[])current.Clone());
return;
}
if (index > n) {
return;
}
current[size++] = index;
Backtrack(index + 1);
size--;
if (n - index >= k - size) {
Backtrack(index + 1);
}
}
}Common mistakes
result.append(current)in Python orresult.add(current)in Java stores a reference to the shared list. Backtracking empties that list later, so every saved group ends up empty. Store a copy withcurrent[:]in Python orcurrent.clone()in Java.- An include with no matching undo, such as
current.append(index)without thecurrent.pop()after the recursive call. The list keeps stale numbers, and later groups come out too long. Undo the include right after the recursive call returns. - Using
n - index > k - len(current)in the exclude check. With n = 3 and k = 2 at index 1 and an empty list, the strict comparison gives 2 > 2, which is false, so the branch is pruned and [2,3] is lost. Use>=. - Checking
index > nbeforelen(current) == k. A group that finishes with n as its last number reaches index n + 1 with a full list, and the early return drops it. Check the size first. - Starting the recursion at 1 each time instead of at index + 1. That produces both [1,2] and [2,1], so the output has duplicates and the wrong count. The start index must only move forward.
Edge cases
- n = 1 and k = 1 returns the single group [[1]].
- k = n, such as n = 5 and k = 5, returns exactly one group, [1,2,3,4,5].
- k = 1 returns n single-element groups in increasing order.
- n = 20 and k = 10 returns 184,756 groups. Each group must be an independent copy, not a reference to the shared list.
- n = 3 and k = 2 must include [2,3]. A strict pruning check fails this case, so test it.
Follow-ups interviewers ask
- Can the groups come out in lexicographic order?
- The current method already does this. It tries include before exclude, and the index only moves forward, so the smallest next number always comes first. For n = 4 and k = 2 the output is [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], which is lexicographic.
- Can you generate the groups without recursion?
- Yes. Keep the current group as an array of k values, and step to the next group each time. Find the rightmost value that can still increase, raise it by one, and reset every value after it to consecutive numbers. Each step costs O(k), and you stop when the first value passes n - k + 1.
- What if the groups do not fit in memory?
- Stop collecting them in a list and yield each group as soon as it completes. In Python, turn the recursion into a generator that yields a copy at each full group. Memory then depends on the recursion depth and one group, which is O(n).
Combinations FAQ
What is the time complexity of Combinations?
The pruned backtracking runs in O(n * C(n, k)) time, where C(n, k) is the number of answers. The bitmask brute force runs in O(n * 2^n) time. The complexity section above counts the work behind both bounds.
Why use backtracking for Combinations?
Each group is a path of include and exclude decisions. Backtracking walks those paths in order and undoes each decision, so it never rebuilds a list from scratch. The pruning check stops it from visiting paths that cannot reach size k.
Can Combinations be solved in O(1) extra space?
No, not in the usual sense. The method has to hold a group of k numbers at once, so the extra space is at least O(k). The recursive version also uses O(n) for the call stack.
Why does my Python result contain empty lists?
You appended the shared current list instead of a copy. Backtracking empties that list before the function returns, so every saved entry ends up empty. Append current[:] when you record a group.
How is Combinations different from Permutations?
Combinations ignore order, so the start index only moves forward. Permutations treat [1,2] and [2,1] as different, so every unused number is a valid next choice. That changes the search tree and the number of results.
Asked at
See which companies ask this — Pro
Related problems
- Subsets · same technique: Subsets (Include/Exclude)
- Letter Combinations of a Phone Number · same technique: Subsets (Include/Exclude)
- Subsets II · same technique: Subsets (Include/Exclude)
- Sum of All Subset XOR Totals · same technique: Subsets (Include/Exclude)
- N-Queens · next harder, same pattern
- Word Search · same pattern: Backtracking Patterns
- Permutations · same pattern: Backtracking Patterns
- Combination Sum · same pattern: Backtracking Patterns
- Generate Parentheses · same pattern: Backtracking Patterns
- Palindrome Partitioning · same pattern: Backtracking Patterns