給定一個無重復(fù)元素的數(shù)組 candidates 和一個目標(biāo)數(shù) target ,找出 candidates 中所有可以使數(shù)字和為 target 的組合。
candidates 中的數(shù)字可以無限制重復(fù)被選取。
說明:
所有數(shù)字(包括 target)都是正整數(shù)。
解集不能包含重復(fù)的組合。
示例 1:
輸入: candidates = [2,3,6,7], target = 7,
所求解集為:
[
[7],
[2,2,3]
]
示例 2:
輸入: candidates = [2,3,5], target = 8,
所求解集為:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
解
典型的回溯算法,按照套路解題即可
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
backtrace(candidates,target,0,res,new ArrayList<Integer>());
return res;
}
public static void backtrace(int[] candidates,int target,int i,List<List<Integer>>res,List<Integer> temp) {
if(target<0)
return ;
if(0==target) {
res.add(new ArrayList<>(temp));
return;
}
for(int start =i;start<candidates.length;start++) {
temp.add(candidates[start]);
// target -=candidates[i];
backtrace(candidates,target-candidates[start],start,res,temp);
temp.remove(temp.size()-1);
}