leetcode39 组合总和
leetcode39 组合总和
思路:
这题也是用回溯,但是考虑到不能重复,所以用一个currentNum记录当前遍历到哪了,按照大小顺序遍历防止重复就行。
class Solution {
//11:10-11:18
public void dfs(int[] candidates,List<List<Integer>> ans,int currentNum,List<Integer> list,int sum,int target){
if (sum==target){
ans.add(new ArrayList<>(list));
}
if(sum>target){
return;
}
if (currentNum>candidates.length){
return;
}
for (int i = currentNum; i < candidates.length; i++) {
int num=candidates[i];
list.add(num);
dfs(candidates,ans,i,list,sum+num,target);
list.remove(list.size()-1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans=new ArrayList<>();
dfs(candidates,ans,0,new ArrayList<>(),0,target);
return ans;
}
}
如果不用currentNum的话,就是遍历所有的组合了(带顺序的)。
class Solution {
//11:10-11:18
public void dfs(int[] candidates,List<List<Integer>> ans,List<Integer> list,int sum,int target){
if (sum==target){
ans.add(new ArrayList<>(list));
}
if(sum>target){
return;
}
for (int i = 0; i < candidates.length; i++) {
int num=candidates[i];
list.add(num);
dfs(candidates,ans,list,sum+num,target);
list.remove(list.size()-1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans=new ArrayList<>();
dfs(candidates,ans,new ArrayList<>(),0,target);
return ans;
}
}