39. Combination Sum
Solution
DFS + backTrace
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> finalResult = new LinkedList<>();
List<Integer> temp = new LinkedList<>();
helper(candidates, 0, finalResult, temp, target);
return finalResult;
}
public void helper(int[] candidates, int index, List<List<Integer>> finalResult, List<Integer> temp, int target){
if(target == 0){
finalResult.add(new LinkedList(temp));
return;
}
if(target < 0) return;
for(int i = index; i < candidates.length; i++){
if(target >= candidates[i]){
target -= candidates[i];
temp.add(candidates[i]);
helper(candidates, i, finalResult, temp, target);
target += candidates[i];
temp.remove(temp.size()-1);
}
}
}
Last updated
Was this helpful?