Algo-Sim › Recursion & Backtracking

Combination Sum II

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

Combinations that sum to a target, each candidate used once, when the input has repeats: Combination Sum with i + 1 and the Subsets II skip.

Problem

Given an array candidates (which may contain repeated values) and a target, return every distinct combination of candidates that adds up to target. Each element may be used at most once, and the answer must not contain the same combination twice.

Constraints

Edge cases to test

Follow-up questions

How does it differ from Combination Sum?
Each candidate is used once (recurse with i + 1), and equal values at the same depth are skipped to avoid repeated combinations.
Why sort first?
Sorting groups duplicates for the skip rule and lets the loop break at the first candidate that overshoots.

Solution

Java

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

List<List<Integer>> combinationSum2(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 (i > start && cand[i] == cand[i - 1]) continue;
        if (cand[i] > remaining) break;
        path.add(cand[i]);
        backtrack(cand, remaining - cand[i], i + 1, path);
        path.remove(path.size() - 1);
    }
}

Python

def combination_sum2(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 i > start and candidates[i] == candidates[i - 1]:
                continue
            if candidates[i] > remaining:
                break
            path.append(candidates[i])
            backtrack(remaining - candidates[i], i + 1, 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>> combinationSum2(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 (i > start && cand[i] == cand[i - 1])
                continue;
            if (cand[i] > remaining)
                break;
            path.push_back(cand[i]);
            backtrack(cand, remaining - cand[i], i + 1, path);
            path.pop_back();
        }
    }
};

More Recursion & Backtracking problems