Video in progress

Strong Middle 🧠 Problem solving

How do you generate all subsets and all permutations of given numbers with backtracking, and how long does it take?

In the recursion I keep the current path in a list: I add an element, go deeper, and remove it on the way back. There are 2ⁿ subsets and n! permutations; the output itself is that large, so there is no faster way.

📖 Answer

Subsets:

static void subsets(int[] a, int start, Deque<Integer> path, List<List<Integer>> out) {
    out.add(new ArrayList<>(path));            // a copy — important
    for (int i = start; i < a.length; i++) {
        path.addLast(a[i]);
        subsets(a, i + 1, path, out);
        path.removeLast();                     // backtrack
    }
}

Permutations:

static void perms(int[] a, boolean[] used, Deque<Integer> path, List<List<Integer>> out) {
    if (path.size() == a.length) { out.add(new ArrayList<>(path)); return; }
    for (int i = 0; i < a.length; i++) {
        if (used[i]) continue;
        used[i] = true; path.addLast(a[i]);
        perms(a, used, path, out);
        path.removeLast(); used[i] = false;
    }
}

The most common bug is writing out.add(path) without a copy. At the end out holds n references to a single empty list.

Give the full complexity: subsets are O(n · 2ⁿ), because copying each one is O(n). Permutations are O(n · n!). At n = 10 the output alone is 3.6 million lists, and at n = 12 it's half a billion, so if the interviewer states a bound on n, choose your approach accordingly.

For input with duplicates ([1, 1, 2]), you sort first and skip when i > start && a[i] == a[i - 1]. The strength of backtracking is pruning: if the path is already invalid (say the sum exceeded a limit), you don't go deeper.