给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
- 所有数字(包括
target)都是正整数。 - 解集不能包含重复的组合。
示例 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 class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
Arrays.sort(candidates);
findSum(candidates, target, 0,0,temp, res);
return res;
}
public void findSum(int[] candidates, int target, int sum, int level,List<Integer> temp, List<List<Integer>> res){
if(sum == target) {
res.add(new ArrayList<>(temp));
return;
} else if(sum > target) {
return;
} else {
for(int i=level;i<candidates.length;i++) {
temp.add(candidates[i]);
findSum(candidates, target, sum+candidates[i], i, temp, res);
temp.remove(temp.size()-1);
}
}
}
}

本文介绍了一种寻找数组中所有可能组合以使数字之和等于目标数的算法。该算法允许数组中的数字无限次重复使用,并确保解集中不包含重复组合。
760

被折叠的 条评论
为什么被折叠?



