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.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 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.
Example 2:
Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1 Output: []
Constraints:
1 <= candidates.length <= 302 <= candidates[i] <= 40candidates are distinct.1 <= target <= 40When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a collection of coin values and a specific target amount of money you want to make. The brute force approach is like exploring every single combination of coins possible to see which groups add up to your target amount.
Here's how the algorithm would work step-by-step:
def combination_sum(candidates, target):
successful_combinations = []
def explore_combinations(current_index, current_group, current_total):
# Stop exploring when the total exceeds our target amount
if current_total > target:
return
# Save the group if the total matches our target amount exactly
if current_total == target:
successful_combinations.append(list(current_group))
return
# Try every candidate starting from the current index to allow reuse
for index in range(current_index, len(candidates)):
current_group.append(candidates[index])
explore_combinations(index, current_group, current_total + candidates[index])
current_group.pop()
explore_combinations(0, [], 0)
return successful_combinationsTo find all ways to reach a specific target sum using a given set of numbers, the optimal approach uses a systematic building process. It explores different paths by repeatedly adding numbers, keeping track of the running total, and smartly backtracking whenever a path exceeds the target or successfully reaches it.
Here's how the algorithm would work step-by-step:
class Solution:
def combinationSum(self, candidate_numbers: list[int], target_goal: int) -> list[list[int]]:
successful_combinations = []
def depth_first_search(start_index: int, current_path: list[int], current_total: int):
# Stop exploring this path early because exceeding the target sum cannot yield a solution.
if current_total > target_goal:
return
if current_total == target_goal:
successful_combinations.append(list(current_path))
return
for candidate_index in range(start_index, len(candidate_numbers)):
chosen_number = candidate_numbers[candidate_index]
current_path.append(chosen_number)
# Allow reusing the same number by keeping the current candidate index in the recursive call.
depth_first_search(candidate_index, current_path, current_total + chosen_number)
current_path.pop()
# Begin the search from the first index with an empty path and a zero starting total.
depth_first_search(0, [], 0)
return successful_combinations| Case | How to Handle |
|---|---|
| Empty candidates array or null input | The recursion naturally terminates immediately and returns an empty list since no elements are available to process. |
| No valid combination can sum to the target | The backtracking function will exhaust all valid paths without adding to the result list, ultimately returning an empty list. |
| Target is smaller than the smallest candidate | The base case or loop condition checks if the remaining target becomes negative, immediately stopping further exploration of that branch. |
| Target is zero | Depending on problem constraints, if the target is zero, the algorithm should return a single empty combination representing the base case. |
| Candidates array contains the number one | This creates a deep recursion tree up to the depth of the target value, which may lead to a stack overflow or time limit exceeded error. |
| Single candidate matching the target exactly | The algorithm adds the single-element combination to the result list and correctly terminates that branch of recursion. |
| Large target value leading to deep recursion | Sorting the candidates array and pruning branches where the current candidate exceeds the remaining target prevents unnecessary deep recursion. |
| Duplicate combinations generated by the search space | Passing the current index forward in recursive calls rather than resetting to zero ensures combinations are built in non-descending order to avoid duplicates. |