Skip to lesson

Combinations and combination sum

A combination is a subset with a specific size or target sum. Once you know the start-index loop from Generating subsets, three tiny tweaks—changing the base case, choosing between i and i + 1 in the recursive call, and sorting so you can break early—solve the entire family of combination problems.

Choosing k of n

Suppose you want all combinations of k numbers chosen from 1..n (written C(n, k) = (n!)/(k!(n - k)!)). Notice that a k-combination is simply a subset of size k!

Example 1 · Brute force: build all 2^n subsets, keep the ones of size k (O(2^n · n) time)

SubsetsFilterK.javaJava
import java.util.ArrayList;import java.util.List;
public class SubsetsFilterK {    static int calls = 0;
    static void build(int next, int n, int k, List<Integer> current, List<List<Integer>> kept) {        calls++;        if (next > n) {            if (current.size() == k) kept.add(new ArrayList<>(current));            return;        }        current.add(next);        build(next + 1, n, k, current, kept);        current.remove(current.size() - 1);        build(next + 1, n, k, current, kept);    }
    public static void main(String[] args) {        List<List<Integer>> kept = new ArrayList<>();        build(1, 6, 4, new ArrayList<>(), kept);        System.out.println("Combinations C(6, 4): " + kept.size());        System.out.println("First 5: " + kept.subList(0, 5));        System.out.println("Calls: " + calls);    }}
Output
Combinations C(6, 4): 15
First 5: [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6]]
Calls: 127

What this code does

  • For n = 6 and k = 4 it makes 127 calls to build all 64 subsets, then keeps the 15 of size 4.
  • It is slow because it also builds the 49 subsets of the wrong size and throws them away at the end.

Example 2 · Optimal: pick forward only and stop when too few numbers remain (O(C(n, k) · k) time)

CombinationsKOfN.javaJava
import java.util.ArrayList;import java.util.List;
public class CombinationsKOfN {    static int callsWithoutPrune = 0;    static int callsWithPrune = 0;
    public static List<List<Integer>> combine(int n, int k, boolean prune) {        List<List<Integer>> results = new ArrayList<>();        backtrack(1, n, k, prune, new ArrayList<>(), results);        return results;    }
    private static void backtrack(int start, int n, int k, boolean prune,                                  List<Integer> current, List<List<Integer>> results) {        if (prune) callsWithPrune++; else callsWithoutPrune++;        if (current.size() == k) {            results.add(new ArrayList<>(current));            return;        }        int needed = k - current.size();        int maxStart = prune ? (n - needed + 1) : n;        for (int i = start; i <= maxStart; i++) {            current.add(i);            backtrack(i + 1, n, k, prune, current, results);            current.remove(current.size() - 1);        }    }
    public static void main(String[] args) {        List<List<Integer>> a = combine(6, 4, false);        List<List<Integer>> b = combine(6, 4, true);        System.out.println("Combinations C(6, 4): " + b.size());        System.out.println("First 5: " + b.subList(0, 5));        System.out.println("Calls without bound pruning: " + callsWithoutPrune);        System.out.println("Calls with bound pruning:    " + callsWithPrune);    }}
Output
Combinations C(6, 4): 15
First 5: [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6]]
Calls without bound pruning: 57
Calls with bound pruning:    35

What this code does

  • At depth 0 (current.size() == 0), we need 4 numbers from 1..6. Starting with i = 4 ([4, 5, 6], only 3 numbers left) can never reach size 4, so maxStart = 6 - 4 + 1 = 3 stops the top-level loop at 3.
  • Both versions produce the exact same C(6, 4) = 15 combinations, but bound pruning cuts the recursive calls from 57 down to 35.
  • This version makes only 35 calls: it never starts a branch that cannot reach size k, so it builds nothing it will throw away.

Instead of recording current at every node of the tree, we only record new ArrayList<>(current) when current.size() == k, and then return immediately so we never go deeper than level k. We can also prune dead branches with one line of arithmetic. If current already has current.size() elements, we still need needed = k - current.size() more elements. From candidate i up to n, there are n - i + 1 numbers left. Whenever n - i + 1 < needed—rearranged as i > n - needed + 1—even taking every remaining number cannot reach size k! Tightening the loop upper bound to i <= n - (k - current.size()) + 1 avoids every doomed call.

For n = 20, k = 15, tightening the loop upper bound from i <= n to i <= n - (k - current.size()) + 1 cuts the number of recursive calls by more than half.

Combination sum with reuse

In Combination Sum I, you are given an array of distinct positive integers candidates and a target sum. You may reuse the same number as many times as you like, and you must return all unique combinations that add up to target.

Example 3 · Combination Sum I: Unlimited Reuse of Candidates

CombinationSumUnlimited.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class CombinationSumUnlimited {    public static List<List<Integer>> combinationSum(int[] candidates, int target) {        Arrays.sort(candidates); // Sort so we can break early        List<List<Integer>> results = new ArrayList<>();        backtrack(candidates, 0, target, new ArrayList<>(), results);        return results;    }
    private static void backtrack(int[] candidates, int start, int remaining,                                  List<Integer> current, List<List<Integer>> results) {        if (remaining == 0) {            results.add(new ArrayList<>(current));            return;        }        for (int i = start; i < candidates.length; i++) {            if (candidates[i] > remaining) {                break; // Sorted: all later candidates are also > remaining!            }            current.add(candidates[i]);            // Pass i (not i + 1) because candidates[i] can be reused:            backtrack(candidates, i, remaining - candidates[i], current, results);            current.remove(current.size() - 1);        }    }
    public static void main(String[] args) {        System.out.println("target = 7: " + combinationSum(new int[]{2, 3, 6, 7}, 7));        System.out.println("target = 8: " + combinationSum(new int[]{2, 3, 5}, 8));    }}
Output
target = 7: [[2, 2, 3], [7]]
target = 8: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]

What this code does

  • Passing i as the next start argument allows candidates[i] to be chosen repeatedly (such as [2, 2, 2, 2]), while preventing earlier indices < i from being revisited.
  • Because candidates is sorted, if (candidates[i] > remaining) break; exits the loop immediately as soon as a candidate overshoots remaining.
  • Passing i (backtrack(candidates, i, remaining - candidates[i], ...)) says: "You may pick candidates[i] again on the next step, or move forward to i + 1, i + 2, ..., but you may never go backward to indices < i."
  • Because you never go backward to indices < i, every combination is generated in non-decreasing index order, making [2, 3, 2] impossible.

How do we allow unlimited reuse of candidates[i] without generating duplicate combinations like [2, 2, 3] and [2, 3, 2]? Keep the start index loop (for (int i = start; i < candidates.length; i++)), and when you recurse after choosing candidates[i], pass i instead of i + 1!

Combination sum without reuse

In Combination Sum II, each element in candidates may be used at most once, and candidates may contain duplicate values (such as [10, 1, 2, 7, 6, 1, 5] with target = 8).

This combines two ideas you already know from Generating subsets:

  1. Sort candidates first so duplicate values sit next to each other.
  2. Skip same-level duplicates: Inside the for (int i = start; ...) loop, write if (i > start && candidates[i] == candidates[i - 1]) continue;.
  3. Pass i + 1 into the recursive call (backtrack(candidates, i + 1, remaining - candidates[i], ...)) so each array index is used at most once.

Example 4 · Combination Sum II: Single Use with Duplicates

CombinationSumSingleUse.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class CombinationSumSingleUse {    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {        Arrays.sort(candidates);        List<List<Integer>> results = new ArrayList<>();        backtrack(candidates, 0, target, new ArrayList<>(), results);        return results;    }
    private static void backtrack(int[] candidates, int start, int remaining,                                  List<Integer> current, List<List<Integer>> results) {        if (remaining == 0) {            results.add(new ArrayList<>(current));            return;        }        for (int i = start; i < candidates.length; i++) {            if (i > start && candidates[i] == candidates[i - 1]) {                continue; // Skip duplicate value at the same decision level            }            if (candidates[i] > remaining) {                break; // Prune remaining larger candidates            }            current.add(candidates[i]);            // Pass i + 1 because each index may be used at most once:            backtrack(candidates, i + 1, remaining - candidates[i], current, results);            current.remove(current.size() - 1);        }    }
    public static void main(String[] args) {        int[] candidates = {10, 1, 2, 7, 6, 1, 5};        System.out.println(combinationSum2(candidates, 8));    }}
Output
[[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]

What this code does

  • Sorting [10, 1, 2, 7, 6, 1, 5] produces [1, 1, 2, 5, 6, 7, 10].
  • [1, 1, 6] is valid because the two 1s sit at different indices (0 and 1) and are picked at different depths (start = 0 and start = 1).
  • However, [1, 2, 5] and [1, 7] are generated only once because at depth 0 (start = 0), when the loop reaches i = 1, i > start is true and candidates[1] == candidates[0], so the second 1 is skipped as a starting element.

Sorting to prune

Sorting to prune means sorting candidates once, before the search, so that a single break skips every candidate that is too big.

Java
Arrays.sort(candidates);                  // once, before the first call
// inside backtrack(candidates, start, remaining, current, results):for (int i = start; i < candidates.length; i++) {    if (candidates[i] > remaining) break; // every later candidate is bigger too    current.add(candidates[i]);    backtrack(candidates, i, remaining - candidates[i], current, results);    current.remove(current.size() - 1);}

If candidates is unsorted, seeing candidates[i] > remaining only tells you to continue to i + 1, because a smaller number might sit later in the array.

If you sort candidates in ascending order first, then as soon as candidates[i] > remaining, every subsequent element candidates[i + 1], candidates[i + 2], ... is also greater than remaining! That means you can break out of the for loop immediately instead of checking the rest of the array or making another recursive call.

Next step

Check your understanding

10 quick questions