Given an array of distinct integers candidates and a target integer, return a list of all unique combinations of candidates where the chosen numbers sum to target. 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.
Output: [[2,2,3],[7]]
Explanation: 2+2+3 = 7 and 7 = 7 are the only two combinations.
Output: [[2,2,2,2],[2,3,3],[3,5]]
We perform backtracking where at each step we try every candidate starting from the current index (allowing reuse). We subtract the chosen candidate from the remaining target and recurse. When the remaining target hits 0 we record the combination. We prune when the remaining target goes negative.
- Sort candidates to enable early termination when a candidate exceeds the remaining target.
- At each recursive call, loop from
startto end; ifcandidates[i] > remaining, break. - Add
candidates[i], recurse with the same indexi(reuse allowed) andremaining - candidates[i]. - Backtrack by removing the last element.
Complexity Analysis:
Time complexity: O(N^(T/M)) where N is the number of candidates, T is the target, and M is the minimum candidate value.
Space complexity: O(T/M) for the recursion depth.