给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
List<Integer> temp=new ArrayList<Integer>();
dfs(candidates,target,ans,temp,0);
return ans;
}
public void dfs(int[] candidates,int target,List<List<Integer>> ans,List<Integer> temp,int num){
if(num==candidates.length){
return;
}
if(target==0){
ans.add(new ArrayList<Integer>(temp));
return;
}
dfs(candidates,target,ans,temp,num+1);
if(target-candidates[num]>=0){
temp.add(candidates[num]);
dfs(candidates,target-candidates[num],ans,temp,num);
temp.remove(temp.size()-1);
}
}
}
思路:回溯法。
先建立一个二重数组用来保存最终的结果组合,再建立一个数组用来临时保存符合条件的数组。
然后进入dfs函数进行运算。
如果当前数a符合target-a>=0,则将该数添加到临时数组中,target-a继续进入下一次dfs。(注意:因为每个数可以无限重复使用,因此num不需要+1)
如果target==0,说明当前临时数组里的数符合条件,将该临时数组加入到二重数组中。
剪枝函数是当前数组的数已被用完。