class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
//创建结果数组
List<List<Integer>> ans = new ArrayList<>();
//调用回溯方法
backtrack(0,candidates,target,new ArrayList<>(),ans);
return ans;
}
//回溯方法
private void backtrack(int start,int[] candidates,int target, ArrayList<Integer> track,List<List<Integer>> ans){
if(target < 0){
return;
}
//满足条件
if(target == 0){
ans.add(new ArrayList<>(track));
}
//选择列表
for(int i = start;i < candidates.length;i++){
//做选择
track.add(candidates[i]);
//回溯
backtrack(i,candidates,target-candidates[i],track,ans);
//撤销选择
track.remove(track.size()-1);
}
}
}