
Given distinct positive integers candidates and a target, return every unique combination whose values sum to the target. A candidate may be used any number of times.
Sort the candidates, then use depth-first backtracking. The helper carries a start index and the remaining sum. Each recursive choice begins at the chosen candidate’s index, so that candidate can be reused; starting there also prevents choices from moving back to a smaller value. Thus each combination is built in nondecreasing order and has exactly one representation, avoiding duplicate permutations.
After choosing a value, subtract it from the remainder, recurse, then remove the value to restore the current path. Since the candidates are positive and sorted, stop the loop as soon as a candidate exceeds the remainder. When the remainder reaches zero, copy the path into the result.
Let V be the number of search states visited and S the number of returned combinations. The search takes O(V + S·L) time, where L is the maximum combination length (copying each result costs up to L); sorting costs O(n log n). The recursion and current path use O(L) auxiliary space, excluding the returned results.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
backtrack(candidates, 0, target, new ArrayList<>(), result);
return result;
}
private void backtrack(
int[] candidates,
int start,
int remaining,
List<Integer> path,
List<List<Integer>> result) {
if (remaining == 0) {
result.add(new ArrayList<>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
int candidate = candidates[i];
if (candidate > remaining) {
break;
}
path.add(candidate);
backtrack(candidates, i, remaining - candidate, path, result);
path.remove(path.size() - 1);
}
}
}