题目链接
题目描述
思路
1.因为不能返回的组合不能重复,因此,应该用index数组下标来便利,防止重复
2.对于某个数来说有两种选法:不选,选(可以多选)
代码
public class t1 {
List<List<Integer>> res=new ArrayList<List<Integer>>();
List<Integer> temp=new ArrayList<Integer>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(0,target,candidates);
return res;
}
private void dfs(int index,int target,int[] candidates){
if(index==candidates.length){
//遍历完未满足,退出
return;
}
if(target==0){
//满足条件,添加到结果中
res.add(new ArrayList<Integer>(temp));
return;
}
//不选,跳过
dfs(index+1,target,candidates);
//提前剪枝
if(target>=candidates[index]){
//选,可以多选,所以index不变
temp.add(candidates[index]);
dfs(index,target-candidates[index],candidates);
temp.remove(temp.size()-1);
}
}
}