
image.png
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates,target,0,0);
return result;
}
private void dfs(int[] candidates, int target, int startIndex, int sum) {
if (sum == target){
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++){
path.add(candidates[i]);
dfs(candidates,target,i,sum+candidates[i]);
path.remove(path.size()-1); // 回溯,移除路径 path 最后一个元素
}
}
}

image.png