class Solution {
int len=0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans=new ArrayList<>();
//DFS模拟一个栈
LinkedList<Integer> path=new LinkedList<>();
len=candidates.length;
// 先将数组排序,这一步很关键
// 排序是为了提前终止搜索
Arrays.sort(candidates);
if(candidates==null||len==0) return ans;
dfs(candidates,target,0,path,ans);
return ans;
}
private void dfs(int[] candidates,int target,int begin,LinkedList<Integer> path,List<List<Integer>> ans){
//结束条件。
if(target==0){
ans.add(new ArrayList<>(path));
return;
}
for(int i=begin;i<len;i++){
if(candidates[i]>target) break;
path.addFirst(candidates[i]);
// 可以重复,传递下去的是 i
dfs(candidates,target-candidates[i],i,path,ans);
path.removeFirst();
}
}
}
class Solution {
int len=0;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans=new ArrayList<>();
//DFS模拟一个栈
LinkedList<Integer> path=new LinkedList<>();
len=candidates.length;
// 先将数组排序,这一步很关键
// 排序是为了提前终止搜索
Arrays.sort(candidates);
if(candidates==null||len==0) return ans;
dfs(candidates,target,0,path,ans);
return ans;
}
private void dfs(int[] candidates,int target,int begin,LinkedList<Integer> path,List<List<Integer>> ans){
//结束条件。
if(target==0){
ans.add(new ArrayList<>(path));
return;
}
for(int i=begin;i<len;i++){
if(candidates[i]>target) break;
//【修改1】 小剪枝
if (i > begin && candidates[i] == candidates[i - 1]) {
continue;
}
path.addFirst(candidates[i]);
//【修改2】 不可以重复,传递下去的是 i+1
dfs(candidates,target-candidates[i],i+1,path,ans);
path.removeFirst();
}
}
}