AlgoTales · Roadmap

Combination sum

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Combination sum asks: which sets of numbers from a list add up to exactly a target, if you may reuse numbers? You add one number at a time, stop when you hit the target, and step back when you overshoot. It models any "make an exact amount" question.

Practical use cases

  • Web app: Gift card and wallet payment split. A checkout page lets a customer pay with gift cards worth 200, 300 and 500 rupees and wants to show every way to make exactly 1,000. The code adds a card, checks the running total, and backs out whenever it exceeds 1,000. The customer sees a short list of valid combinations instead of guessing.
  • Web app: Bundle builder under a budget. A shopping site has a "build your own hamper" page with items priced 150, 250 and 400. Marketing wants a list of every hamper that costs exactly 1,000. Trying items one by one and stopping early when the total gets too high avoids checking thousands of hopeless baskets. Marketing can then pick the three or four most attractive hampers from the list and show them as ready-made offers on the home page without anyone counting by hand.
  • System: Cutting material and subset puzzles. A workshop cuts planks of fixed lengths to fill a 10-metre rail. Each valid set of cuts is one combination that adds to 10. The same method sits behind subset-sum puzzles in accounting software. Cutting off a branch the moment the total is too big is what keeps these searches from exploring millions of pointless combinations, and it is the heart of backtracking.

The story: Exact Change at the Kirana Store

The kirana store owner, Mr. Iyer, had a funny rule: "I only accept exact change." Mira wanted to buy a pencil box that cost 8 rupees, and her pocket held plenty of 2, 3 and 5 rupee coins, as many of each as she liked.

"How many ways can I pay?" she wondered. She began adding coins: 2 and 2 and 2 and 2 made 8. Good. 2 and 3 and 3 made 8. Good. Then 5 and 3 made 8. Good. But sometimes she added too far, like 5 and 5, and had to take the last coin back and try a smaller one.

Kabir noticed two things. First: a coin can be used again and again, so after choosing a 2 you may choose 2 again. Second: 2 then 3 is the same payment as 3 then 2, so he made a rule: never go back to a smaller coin. Once you move on to the 3s, you stay at 3 or higher.

With those two rules, Mira found exactly three ways, with no duplicates, and the shopkeeper nodded. This is combination sum: backtracking where each choice reduces the remaining amount, and going over means stop and undo.

How to spot this problem, and where you need it

You need every way to reach an exact total using numbers from a list, and you may use the same number more than once.

Signs you need it

  • The problem has a target number and a list of allowed values, and asks for "all combinations" that add up to the target.
  • You are looping through amounts and the same price or coin may be used again and again.
  • Your first attempt produces duplicates like 2+3 and 3+2, which means order should not matter.

Where to use it in a project

  • Showing a customer all valid ways to split a bill across vouchers, wallets or gift cards.
  • Suggesting product bundles or packaging sizes that hit an exact price or weight.

The solution

Sort the numbers first. Start with an empty selection and a running total of zero. Try adding each number from the current one onwards, which stops duplicate orderings. If the total equals the target, save the selection. If it goes over the target, stop right there and step back, because larger numbers will only go further over. Otherwise carry on adding. Stepping back and trying the next number is backtracking.

Payoff: Before: checking every basket of every size. After: the search stops as soon as a total passes 1,000, so only a few dozen sensible baskets are tried.

Explain it like I am 8

You need to pay exactly 8 rupees with coins of 2, 3 and 5, and you have lots of each. Drop coins in your hand one by one. If you reach 8 you found a way. If you go past 8, take the last coin out and try a different one. Do not try the same coins in a different order, they count as one way.

How it works, step by step

  1. Keep a path of chosen numbers and the remaining amount (target minus the path total).
  2. Success: remaining is exactly 0, so save a copy of the path.
  3. Failure: remaining is below 0, we overshot. Stop and go back.
  4. Loop over the candidates from start onward. Choose one, then explore with the same start = i (reuse allowed).
  5. Un-choose by removing it. Starting from i prevents duplicates such as [2,3,3] and [3,2,3].

The code in four languages

PHP

<?php
// Every combination of candidates (each reusable) that adds up to $target.
function combinationSum(array $candidates, int $target): array {
    $result = [];
    $path = [];
    $dfs = function (int $start, int $remaining) use (&$dfs, &$result, &$path, $candidates) {
        if ($remaining < 0) return;               // overshot: dead end
        if ($remaining === 0) {                   // exact change: save a copy
            $result[] = $path;
            return;
        }
        for ($i = $start; $i < count($candidates); $i++) {
            $path[] = $candidates[$i];            // choose
            $dfs($i, $remaining - $candidates[$i]);   // explore (same coin allowed again)
            array_pop($path);                     // un-choose
        }
    };
    $dfs(0, $target);
    return $result;
}

foreach (combinationSum([2, 3, 5], 8) as $c) {
    echo implode(' + ', $c) . " = 8\n";
}

JavaScript

// Every combination of candidates (each reusable) that adds up to target.
function combinationSum(candidates, target) {
  const result = [];
  const path = [];
  function dfs(start, remaining) {
    if (remaining < 0) return;                // overshot: dead end
    if (remaining === 0) {                    // exact change: save a copy
      result.push([...path]);
      return;
    }
    for (let i = start; i < candidates.length; i++) {
      path.push(candidates[i]);               // choose
      dfs(i, remaining - candidates[i]);      // explore (same coin allowed again)
      path.pop();                             // un-choose
    }
  }
  dfs(0, target);
  return result;
}

for (const c of combinationSum([2, 3, 5], 8)) {
  console.log(c.join(' + ') + ' = 8');
}

Java

import java.util.*;

public class Main {
    // Every combination of candidates (each reusable) that adds up to target.
    static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(candidates, 0, target, new ArrayList<>(), result);
        return result;
    }

    static void dfs(int[] candidates, int start, int remaining, List<Integer> path, List<List<Integer>> result) {
        if (remaining < 0) return;                       // overshot: dead end
        if (remaining == 0) {                            // exact change: save a copy
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            path.add(candidates[i]);                     // choose
            dfs(candidates, i, remaining - candidates[i], path, result);   // explore (same coin allowed again)
            path.remove(path.size() - 1);                // un-choose
        }
    }

    public static void main(String[] args) {
        for (List<Integer> c : combinationSum(new int[]{2, 3, 5}, 8)) {
            StringJoiner sj = new StringJoiner(" + ");
            for (int x : c) sj.add(String.valueOf(x));
            System.out.println(sj + " = 8");
        }
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// combinationSum returns every combination of candidates (each reusable) that adds up to target.
func combinationSum(candidates []int, target int) [][]int {
	var result [][]int
	var path []int
	var dfs func(start, remaining int)
	dfs = func(start, remaining int) {
		if remaining < 0 { // overshot: dead end
			return
		}
		if remaining == 0 { // exact change: save a copy
			result = append(result, append([]int(nil), path...))
			return
		}
		for i := start; i < len(candidates); i++ {
			path = append(path, candidates[i]) // choose
			dfs(i, remaining-candidates[i])    // explore (same coin allowed again)
			path = path[:len(path)-1]          // un-choose
		}
	}
	dfs(0, target)
	return result
}

func main() {
	for _, c := range combinationSum([]int{2, 3, 5}, 8) {
		parts := []string{}
		for _, x := range c {
			parts = append(parts, strconv.Itoa(x))
		}
		fmt.Println(strings.Join(parts, " + ") + " = 8")
	}
}

Time: O(n^(T/m)) · Extra space: O(T/m). Here T is the target and m the smallest coin: the deepest path uses the smallest coin over and over. Sorting the coins lets you stop a loop early once a coin is too big.

Watch out for

  • Recursing with i + 1 when coins may be reused, so [2,2,2,2] is never found.
  • Recursing with 0 instead of i, which lists [2,3,3] and [3,2,3] as different answers.
  • Forgetting the remaining < 0 check, which makes the recursion run forever.

Quick check

  1. Candidates [2,3,5], target 8. Which is a valid answer?
    • [2, 2, 2, 2]
    • [5, 5]
    • [2, 5]
    • [3, 3, 3]
  2. Why does the recursive call pass i instead of i + 1?
    • So the same coin can be used again
    • To skip the coin
    • To sort the answers
  3. What stops the search along a path?
    • Remaining equals 0 (success) or goes below 0 (overshoot)
    • Reaching the end of the array
    • A timer