Lesson 24 · Core algorithms

Subsets and Combinations

A subset is any selection of items, in no particular order; a combination is a subset of a fixed size k. Both are listed by the same recursive loop: record the current selection, then try adding each item that comes after the last one chosen. Moving only forward is what stops {1, 2} and {2, 1} from both appearing.

Subsets and Combinations concept diagramThe 16 subsets of a, b, c, d arranged in five rows by size: the empty set; a, b, c, d; the six pairs ab, ac, ad, bc, bd, cd; the four triples; and abcd. Lines join subsets that differ by one item. The rows hold 1, 4, 6, 4 and 1 subsets, which are C(4, 0) to C(4, 4). The pairs row is highlighted as the 6 combinations of 4 choose 2, and the total is 2 to the 4th, 16 subsets.{ }size 0: C(4, 0) = 1choose nothing{a}{b}{c}{d}size 1: C(4, 1) = 4choose 1{ab}{ac}{ad}{bc}{bd}{cd}size 2: C(4, 2) = 64 choose 2{abc}{abd}{acd}{bcd}size 3: C(4, 3) = 4choose 3{abcd}size 4: C(4, 4) = 1take all1 + 4 + 6 + 4 + 1 = 16 = 2⁴ subsets · each item in or out · lines join sets that differ by one item
1

Selections, Not Orderings

Subsets and combinations both pick items without caring about order. {1, 2} and {2, 1} are the same subset. That is the one difference from permutations, where 12 and 21 are different answers, and it changes the code in one place.

A subset is any selection, from none of the items to all of them. Every item is either in or out, so n items have 2ⁿ subsets. The set of all of them is called the power set. A combination is a subset of a given size k; the number of them is C(n, k) = n! / (k! · (n − k)!), read "n choose k". The combinatorics lesson covers the counting; this lesson lists them.

Listing subsets and combinations uses one idea: build each selection in increasing index order. If the last item taken was at index i, the next can only come from index i + 1 onward. Each selection then has exactly one way to be built, so none repeats.

  • Subset: any selection, 2ⁿ of them
  • Combination: a selection of exactly k items, C(n, k) of them
  • Same items in a different order = the same selection
2

Every Subset with a Start Index

  1. Call build(start) with the current path
  2. Record a copy of the path: it is a subset
  3. For each index i from start to n − 1: append items[i], call build(i + 1), pop

There is no base case. Every call records its path, and the loop simply does not run when start reaches n. On [1, 2, 3] the subsets come out as {}, {1}, {1, 2}, {1, 2, 3}, {1, 3}, {2}, {2, 3}, {3}: eight calls, one subset each.

The start index is what makes it correct. When the root loop moves on to 2, item 1 is behind start and is never offered again, so {2, 1} cannot be built. Remove the start index, loop from 0 and skip items already in the path, and the function lists ordered selections instead: 16 results for three items, half of them repeats.

Time is O(n · 2ⁿ): 2ⁿ subsets, each copied in O(n). The recursion is at most n deep. Another view of the same search is a binary choice per item, include it or skip it, which builds the same 2ⁿ leaves with only the leaves recorded.

  • Record first, then extend: every call is one subset
  • Loop from start, never from 0
  • O(n · 2ⁿ) time, O(n) extra space besides the output
3

Combinations Using Backtracking

Combinations change two lines of the subset function. Record only when the path holds k items, and return right after recording, because a longer path is no use. On 1..4 with k = 2 the output is {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}: six, which is C(4, 2) = 4! / (2! · 2!).

A bound on the loop prunes branches that cannot finish. With len(path) items chosen, k − len(path) more are needed, so the next pick can be at most n − (k − len(path)) + 1 (counting items from 1). For 4 choose 2 this stops the first pick at 3, because a pair cannot start with 4. The saving grows when k is close to n: listing n choose k combinations for 20 choose 15 takes 54,264 calls with the bound and 1,042,380 without it.

The cost is O(k · C(n, k)) for the output plus the internal calls. C(n, k) is largest at k = n/2, where it is roughly 2ⁿ divided by √n, so choosing half the items is almost as expensive as listing every subset.

  • Record and return when the path has k items
  • Loop while i ≤ n − (k − len(path)) + 1
  • Combination Sum and similar problems add a running total and stop when it overshoots
Key reference

Terms, operations, and practical uses

Key terms

  • Power setThe set of all 2ⁿ subsets of n items.
  • C(n, k)The number of ways to choose k of n items: n! / (k! · (n − k)!).
  • Start indexWhere the next pick may begin; it keeps every selection in increasing order.
  • BitmaskAn integer whose bit j marks whether item j is chosen.
Implementation

Code in Python, C++ and Java

def subsets(items):
    result, path = [], []

    def build(start):
        result.append(path[:])
        for i in range(start, len(items)):
            path.append(items[i])
            build(i + 1)
            path.pop()

    build(0)
    return result


def combinations(n, k, prune=True):
    result, path, calls = [], [], 0

    def build(start):
        nonlocal calls
        calls += 1
        if len(path) == k:
            result.append(path[:])
            return
        last = n - (k - len(path)) + 1 if prune else n
        for i in range(start, last + 1):
            path.append(i)
            build(i + 1)
            path.pop()

    build(1)
    return result, calls


def subsets_by_mask(items):
    n = len(items)
    return [[items[j] for j in range(n) if mask >> j & 1] for mask in range(1 << n)]


def combinations_by_mask(n, k):
    picks = []
    for mask in range(1 << n):
        if bin(mask).count("1") == k:
            picks.append([j + 1 for j in range(n) if mask >> j & 1])
    return picks


def text(groups):
    return " ".join("{" + "".join(map(str, g)) + "}" for g in groups)


print("subsets of 1 2 3:", text(subsets([1, 2, 3])))
print("count:", len(subsets([1, 2, 3])))
combos, calls = combinations(4, 2)
print("4 choose 2:", text(combos), f"({calls} calls with pruning)")
print("calls without pruning:", combinations(4, 2, prune=False)[1])
print("20 choose 15 calls:", combinations(20, 15)[1], "vs", combinations(20, 15, prune=False)[1])
print("subsets by bitmask:", text(subsets_by_mask([1, 2, 3])))
print("4 choose 2 by bitmask:", text(combinations_by_mask(4, 2)))
print("n = 0:", subsets([]), "| k = 0:", combinations(3, 0)[0], "| k > n:", combinations(2, 3)[0])
#include <iostream>
#include <string>
#include <vector>
using namespace std;

using Groups = vector<vector<int>>;

void subsetsFrom(const vector<int>& items, size_t start, vector<int>& path, Groups& result) {
    result.push_back(path);
    for (size_t i = start; i < items.size(); i++) {
        path.push_back(items[i]);
        subsetsFrom(items, i + 1, path, result);
        path.pop_back();
    }
}

Groups subsets(const vector<int>& items) {
    Groups result;
    vector<int> path;
    subsetsFrom(items, 0, path, result);
    return result;
}

void combine(int n, int k, int start, bool prune, vector<int>& path, Groups& result, long long& calls) {
    calls++;
    if ((int)path.size() == k) {
        result.push_back(path);
        return;
    }
    int last = prune ? n - (k - (int)path.size()) + 1 : n;
    for (int i = start; i <= last; i++) {
        path.push_back(i);
        combine(n, k, i + 1, prune, path, result, calls);
        path.pop_back();
    }
}

pair<Groups, long long> combinations(int n, int k, bool prune = true) {
    Groups result;
    vector<int> path;
    long long calls = 0;
    combine(n, k, 1, prune, path, result, calls);
    return {result, calls};
}

Groups subsetsByMask(const vector<int>& items) {
    Groups out;
    int n = items.size();
    for (int mask = 0; mask < (1 << n); mask++) {
        vector<int> g;
        for (int j = 0; j < n; j++)
            if (mask >> j & 1) g.push_back(items[j]);
        out.push_back(g);
    }
    return out;
}

Groups combinationsByMask(int n, int k) {
    Groups out;
    for (int mask = 0; mask < (1 << n); mask++) {
        if (__builtin_popcount(mask) != k) continue;
        vector<int> g;
        for (int j = 0; j < n; j++)
            if (mask >> j & 1) g.push_back(j + 1);
        out.push_back(g);
    }
    return out;
}

string text(const Groups& groups) {
    string s;
    for (size_t i = 0; i < groups.size(); i++) {
        s += i ? " {" : "{";
        for (int x : groups[i]) s += to_string(x);
        s += "}";
    }
    return s;
}

string brackets(const Groups& groups) {
    string s = "[";
    for (size_t i = 0; i < groups.size(); i++) {
        s += i ? ", [" : "[";
        for (size_t j = 0; j < groups[i].size(); j++) s += (j ? ", " : "") + to_string(groups[i][j]);
        s += "]";
    }
    return s + "]";
}

int main() {
    cout << "subsets of 1 2 3: " << text(subsets({1, 2, 3})) << "\n";
    cout << "count: " << subsets({1, 2, 3}).size() << "\n";
    auto [combos, calls] = combinations(4, 2);
    cout << "4 choose 2: " << text(combos) << " (" << calls << " calls with pruning)\n";
    cout << "calls without pruning: " << combinations(4, 2, false).second << "\n";
    cout << "20 choose 15 calls: " << combinations(20, 15).second << " vs " << combinations(20, 15, false).second << "\n";
    cout << "subsets by bitmask: " << text(subsetsByMask({1, 2, 3})) << "\n";
    cout << "4 choose 2 by bitmask: " << text(combinationsByMask(4, 2)) << "\n";
    cout << "n = 0: " << brackets(subsets({})) << " | k = 0: " << brackets(combinations(3, 0).first)
         << " | k > n: " << brackets(combinations(2, 3).first) << "\n";
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static long calls;

    static void subsetsFrom(int[] items, int start, List<Integer> path, List<List<Integer>> result) {
        result.add(new ArrayList<>(path));
        for (int i = start; i < items.length; i++) {
            path.add(items[i]);
            subsetsFrom(items, i + 1, path, result);
            path.remove(path.size() - 1);
        }
    }

    static List<List<Integer>> subsets(int[] items) {
        List<List<Integer>> result = new ArrayList<>();
        subsetsFrom(items, 0, new ArrayList<>(), result);
        return result;
    }

    static void combine(int n, int k, int start, boolean prune, List<Integer> path, List<List<Integer>> result) {
        calls++;
        if (path.size() == k) {
            result.add(new ArrayList<>(path));
            return;
        }
        int last = prune ? n - (k - path.size()) + 1 : n;
        for (int i = start; i <= last; i++) {
            path.add(i);
            combine(n, k, i + 1, prune, path, result);
            path.remove(path.size() - 1);
        }
    }

    static List<List<Integer>> combinations(int n, int k, boolean prune) {
        List<List<Integer>> result = new ArrayList<>();
        calls = 0;
        combine(n, k, 1, prune, new ArrayList<>(), result);
        return result;
    }

    static List<List<Integer>> subsetsByMask(int[] items) {
        List<List<Integer>> out = new ArrayList<>();
        int n = items.length;
        for (int mask = 0; mask < (1 << n); mask++) {
            List<Integer> g = new ArrayList<>();
            for (int j = 0; j < n; j++)
                if ((mask >> j & 1) == 1) g.add(items[j]);
            out.add(g);
        }
        return out;
    }

    static List<List<Integer>> combinationsByMask(int n, int k) {
        List<List<Integer>> out = new ArrayList<>();
        for (int mask = 0; mask < (1 << n); mask++) {
            if (Integer.bitCount(mask) != k) continue;
            List<Integer> g = new ArrayList<>();
            for (int j = 0; j < n; j++)
                if ((mask >> j & 1) == 1) g.add(j + 1);
            out.add(g);
        }
        return out;
    }

    static String text(List<List<Integer>> groups) {
        StringBuilder sb = new StringBuilder();
        for (List<Integer> g : groups) {
            sb.append(sb.length() > 0 ? " {" : "{");
            for (int x : g) sb.append(x);
            sb.append('}');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println("subsets of 1 2 3: " + text(subsets(new int[]{1, 2, 3})));
        System.out.println("count: " + subsets(new int[]{1, 2, 3}).size());
        List<List<Integer>> combos = combinations(4, 2, true);
        System.out.println("4 choose 2: " + text(combos) + " (" + calls + " calls with pruning)");
        combinations(4, 2, false);
        System.out.println("calls without pruning: " + calls);
        combinations(20, 15, true);
        long pruned = calls;
        combinations(20, 15, false);
        System.out.println("20 choose 15 calls: " + pruned + " vs " + calls);
        System.out.println("subsets by bitmask: " + text(subsetsByMask(new int[]{1, 2, 3})));
        System.out.println("4 choose 2 by bitmask: " + text(combinationsByMask(4, 2)));
        System.out.println("n = 0: " + subsets(new int[]{}) + " | k = 0: " + combinations(3, 0, true)
                + " | k > n: " + combinations(2, 3, true));
    }
}
Watch it run

Step through it

Running on [1, 2, 3]; then n = 4, k = 2

subsets of [1, 2, 3] · record at every call · the loop only moves forward123start = 0PATH{}RESULTS{}calls 1 · subsets 1
Step 1

Record the empty subset

Each call first records the path, then tries to extend it. The first call has an empty path, so {} goes in straight away: picking nothing is one valid subset. Its loop will offer 1, 2 and 3 as the next item.

Output
1 / 14
4

Bitmasking Subsets

Bitmasking subsets needs no recursion. Number the items 0 to n − 1 and count from 0 to 2ⁿ − 1. In each number, bit j says whether item j is in. For three items, 5 is 101 in binary, which selects items 0 and 2. Every number is a different subset, and every subset is some number, so the loop lists the power set exactly once.

Combinations follow by keeping only the masks with k bits set. That is short to write but always examines all 2ⁿ masks, so it suits small n (up to about 20, a million masks). For larger n with small k, the backtracking loop visits only the C(n, k) answers and the pruned paths to them.

Masks also make good keys. A subset stored as one integer can index an array, which is the basis of bitmask dynamic programming.

Two ways to list subsets of n items
Start-index recursionBitmask loop
Order of output{1}, {1,2}, {1,2,3}, {1,3}, …{1}, {2}, {1,2}, {3}, …
Exactly k itemsPrunes, visits about C(n, k) answersChecks all 2ⁿ masks
Repeated valuesSort and skip equal siblingsProduces duplicates
LimitStack depth nn up to about 20 to 30 (bits in an integer)
  • Mask m includes item j when (m >> j) & 1 is 1
  • Count bits with popcount to filter size k
  • Use the recursion when values repeat or n is large
5

Repeats and Edge Cases

If the input holds equal values, [1, 2, 2] for example, the plain function lists {1, 2} twice. Sort first, then inside the loop skip index i when i > start and items[i] equals items[i − 1]. The first copy of a value at each level is tried; later copies at the same level are skipped, so each distinct selection appears once.

Check the boundaries. n = 0 gives one subset, the empty one. k = 0 gives one combination, choosing nothing, and k > n gives none, matching C(n, 0) = 1 and C(n, k) = 0 for k > n. As always, record a copy of the path, never the shared list itself.

  • Duplicates: sort, then skip a value equal to its left neighbour at the same level
  • n = 0 → [[]]; k = 0 → [[]]; k > n → []
  • Test the count against 2ⁿ or C(n, k) on small inputs
6

Practice and Next Steps

Do these in order: plain subsets, then a fixed size, then repeats and targets. The backtracking lesson shows the same loop with stronger pruning on N-Queens.