BackendML

Combination Sum II

Medium3 min read
The Combination Sum II problem requires finding all unique combinations of numbers that add up to a given target, where each number can be used at most once.

Problem

Given a collection of candidates and an integer target, return all unique combinations of candidates where the chosen numbers sum to target.

Each number in candidates may be used only once. The input may contain duplicate numbers, but the result must not contain duplicate combinations.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

candidates = [10,1,2,7,6,1,5]
target = 8

Output

[[1,1,6],[1,2,5],[1,7],[2,6]]

Solution

This solution uses Backtracking to explore all possible combinations. The candidates are first sorted so that duplicate values appear next to each other.

At each step, a candidate is added to the current combination and the recursion continues from the next index. Using i + 1 ensures that the same array element cannot be selected again.

If the remaining target becomes 0, a valid combination has been found and is added to the result. If the remaining target becomes negative, the path is stopped.

Since the input can contain duplicate values, the condition i > start && candidates[i] == candidates[i - 1] skips duplicate values at the same recursion level. This prevents generating the same combination more than once while still allowing duplicate values to be used when they occur at different positions in the input.

Because the candidates are sorted, the recursion can also stop early when candidates[i] > remaining.
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(candidates);

    backtrack(candidates, target, 0, new ArrayList<>(), result);
    return result;
}

private void backtrack(int[] candidates, int remaining, int start,
        List<Integer> current, List<List<Integer>> result) {

    // A valid combination is found.
    if (remaining == 0) {
        result.add(new ArrayList<>(current));
        return;
    }

    for (int i = start; i < candidates.length; i++) {

        // Skip duplicate values at the same recursion level.
        if (i > start && candidates[i] == candidates[i - 1]) {
            continue;
        }

        // No later value can produce a valid combination.
        if (candidates[i] > remaining) {
            break;
        }

        // Choose the current candidate.
        current.add(candidates[i]);

        // Move to the next index so the same element is not reused.
        backtrack(candidates, remaining - candidates[i],
                i + 1, current, result);

        // Undo the choice.
        current.remove(current.size() - 1);
    }
}

Complexity

Sorting the candidates takes O(n log n). The backtracking process can explore up to O(2n) subsets in the worst case. Therefore, excluding the cost of copying the output, the backtracking time complexity is O(2n).

Including the cost of storing each combination, the total time can be O(n × 2n) in the worst case. The recursion depth is at most O(n), excluding the space required for the output.

Comments

No comments yet. Ask a question or share what helped.