在这里插入图片描述](https://img-blog.csdnimg.cn/20191118195744811.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2theWxlZV9zdHVkeQ==,size_16,color_FFFFFF,t_70)
讨论区的解法基本都是回溯和递归,说到回溯递归基本就一句话“自己调用自己”,而实际运行过程总是让人很晕。现为了方便详细分析整个算法过程,选取candidates数组只包含两个数{2,4};target=6;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
getResult(result, new ArrayList<Integer>(), candidates, target, 0);
return result;
}
private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
if(target > 0){
for(int i = start; i < candidates.length && target >= candidates[i]; i++){
cur.add(candidates[i]);
getResult(result, cur, candidates, target - candidates[i], i);
cur.remove(cur.size() - 1);
}//for
}//if
else if(target == 0 ){
result.add(new ArrayList<Integer>(cur));
}//else if
}
}