Skip to content
AI360Xpert
Back to Backtracking
Medium

Combination Sum

Given an array of distinct integers `candidates` and a target integer `target`, return a list of all unique combinations of `candidates` where the chosen numbers sum to `target`. You may return the combinations in any order. The same number may be chosen from `candidates` an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.

Examples

Input:candidates = [2,3,6,7], target = 7
Output:[[2,2,3],[7]]
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.
Input:candidates = [2,3,5], target = 8
Output:[[2,2,2,2],[2,3,3],[3,5]]
There are three different ways to sum to 8 using the given candidates.

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of `candidates` are distinct.
  • 1 <= target <= 40

Backtracking

Approach

We explore all possible combinations by either choosing the current candidate or moving to the next candidate. Since a candidate can be used multiple times, when we choose a candidate, we do not increment the index for the next recursive step. If the current sum exceeds the target, we backtrack. If it equals the target, we add the combination to our result.

Complexity Analysis

Time Complexity
O(2^(target/min_candidate))
Space Complexity
O(target/min_candidate)

The recursion tree has a maximum depth of target/min_candidate. In the worst case, the number of nodes in the recursion tree can be exponential.

Solution.java
class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>> result = new ArrayList<>();        backtrack(0, candidates, target, new ArrayList<>(), result);        return result;    }        private void backtrack(int index, int[] candidates, int target, List<Integer> current, List<List<Integer>> result) {        // Base case: exact sum found        if (target == 0) {            result.add(new ArrayList<>(current));            return;        }                // Base case: sum exceeded or out of bounds        if (target < 0 || index >= candidates.length) {            return;        }                // Decision 1: Include the current candidate        // We stay at the same index because we can reuse the element        current.add(candidates[index]);        backtrack(index, candidates, target - candidates[index], current, result);                // Decision 2: Exclude the current candidate and move to the next        current.remove(current.size() - 1);        backtrack(index + 1, candidates, target, current, result);    }}