此题为经典回溯算法
class Solution {
List<List<Integer>> res=new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
//对数组从小到大进行排序
Arrays.sort(candidates);
//设置路径List集合
List<Integer> path=new ArrayList<>();
//借用回溯算法
backstrack(candidates,target,path,0);
//返回结果集
return res;
}
public void backstrack(int [] candidates,int target,List<Integer> path,int begin){
if(target==0){
//将路径添加到结果集中
res.add(new ArrayList<>(path));
return ;
}
for(int i=begin;i<candidates.length;i++){
if(candidates[i]<=target){
//将该数添加到路径中
path.add(candidates[i]);
//进行下一次回溯
backstrack(candidates,target-candidates[i],path,i);
//回溯失败,
path.remove(path.size()-1);
}
}
}
}
结果