class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(target,candidates,0,0);
return res;
}
public void dfs(int target,int[] candidates,int cur,int start){
if(cur > target ) return;
if(cur == target){
res.add(new ArrayList<>(list));
return;
}
for(int i=start;i<candidates.length;i++){//从start开始
list.add(candidates[i]);
dfs(target,candidates,cur+candidates[i],i);//这里是i不是i+1
list.remove(list.size()-1);
}
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(target,candidates,0,0);
return res;
}
public void dfs(int target,int[] candidates,int cur,int start){
if(cur > target) return;
if(cur == target){
res.add(new ArrayList(list));
return;
}
for(int i=start;i<candidates.length;i++){//从start开始
if(i!=start && candidates[i] == candidates[i-1]) continue;//去重
list.add(candidates[i]);
dfs(target,candidates,cur+candidates[i],i+1);//i+1不重复取
list.remove(list.size()-1);
}
}
}