解法(回溯方法)
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target){
// 判断不合法的情况
if(candidates == null || candidates.length == 0){
return null;
}
// 新建List
List<List<Integer>> result = new ArrayList<>();
backtracing(candidates, target, 0, new ArrayDeque<>(), result);
return result;
}
public void backtracing(int[] candidates, int target, int start, Deque<Integer> solution, List<List<Integer>> result){
// 递归结束的条件
if (target < 0){
return;
}
// 回溯满足的条件
if (target == 0){
result.add(new ArrayList<>(solution));
return;
}
// 递归
for(int i = start; i < candidates.length; i++){
solution.push(candidates[i]);
backtracing(candidates, target - candidates[i], i, solution, result);
// 移除已递归元素
solution.pop();
}
}
}
避免重复,所以应该从自己开始,start