问题描述
力扣https://leetcode.cn/problems/Ygoe9J/
解题思路
实例代码
class Solution {
private LinkedList<List<Integer>>res=new LinkedList<>();
private LinkedList<Integer>data=new LinkedList<>();
private int sum=0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
reverse(candidates,target,0);
return res;
}
public void reverse(int []candidates,int target,int index){
//递归出口
if(index==candidates.length){
return;
}
if(target==0){
res.add(new LinkedList(data));
return;
}
//不选择当前数字
reverse(candidates,target,index+1);
//选择当前数字
if(target-candidates[index]>=0){
data.add(candidates[index]);
reverse(candidates,target-candidates[index],index);
//回溯
data.removeLast();
}
}
}
问题描述
力扣https://leetcode.cn/problems/4sjJUc/
解题思路
实例代码
class Solution {
private LinkedList<List<Integer>>res=new LinkedList<>();
private LinkedList<Integer>data=new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
reverse(candidates,0,target);
return res;
}
public void reverse(int[]candidates,int index,int target){
if(target==0){
res.add(new LinkedList(data));
return;
}
for(int i=index;i<candidates.length;++i){
if(candidates[i]>target){
break;
}
if(i>index&&candidates[i]==candidates[i-1]){
continue;
}
data.add(candidates[i]);
reverse(candidates,i+1,target-candidates[i]);
data.removeLast();
}
}
}