Algo-Sim › Recursion & Backtracking

Combination Sum

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Combinations that sum to a target with unlimited reuse: recurse with the same index, and stop the loop at the first candidate that overshoots.

Problem

Given distinct positive integers candidates and a target, return every distinct combination of candidates that adds up to target. A candidate may be used any number of times; combinations that differ only in order are the same.

Constraints

Edge cases to test

Follow-up questions

Why recurse with the same index?
It allows unlimited reuse of a candidate while still building each combination in non-decreasing order, so none repeats.
What if you only need the count?
Use Coin Change II’s DP over amounts: O(n·target).

Solution

Java

List<List<Integer>> result = new ArrayList<>();

List<List<Integer>> combinationSum(int[] candidates, int target) {
    Arrays.sort(candidates);
    backtrack(candidates, target, 0, new ArrayList<>());
    return result;
}

void backtrack(int[] cand, int remaining, int start, List<Integer> path) {
    if (remaining == 0) {
        result.add(new ArrayList<>(path));
        return;
    }
    for (int i = start; i < cand.length; i++) {
        if (cand[i] > remaining) break;
        path.add(cand[i]);
        backtrack(cand, remaining - cand[i], i, path);
        path.remove(path.size() - 1);
    }
}

Python

def combination_sum(candidates, target):
    candidates = sorted(candidates)
    result = []

    def backtrack(remaining, start, path):
        if remaining == 0:
            result.append(path[:])
            return
        for i in range(start, len(candidates)):
            if candidates[i] > remaining:
                break
            path.append(candidates[i])
            backtrack(remaining - candidates[i], i, path)
            path.pop()

    backtrack(target, 0, [])
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> result = {};

    vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<int> path;
        backtrack(candidates, target, 0, path);
        return result;
    }

    void backtrack(vector<int> &cand, int remaining, int start, vector<int> &path) {
        if (remaining == 0) {
            result.push_back(path);
            return;
        }
        for (int i = start; i < int(cand.size()); i++) {
            if (cand[i] > remaining)
                break;
            path.push_back(cand[i]);
            backtrack(cand, remaining - cand[i], i, path);
            path.pop_back();
        }
    }
};

More Recursion & Backtracking problems