39. 组合总和
给定一个无重复元素的数组 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]
]
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500
思路
1 先将候选数字排序,便于剪枝
2 画树
3 递归出口
符合结果:子集每加入一个数字,target减去相应的数字,当target为0时,表示改子集满足条件,是一个结果(反向思维,相加也行,比较sum和target)
剪枝条件:target-候选数字小于0时,后面比它更大的就不用计算了,例如图中的2-2-2-2与2-2-2-3,直接break
代码
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
func(new LinkedList<>(), target, 0, candidates, res);
return res;
}
private void func(Deque<Integer> sub, int target, int from, int[] candidates,
List<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList<>(sub));
}
for (int i = from; i < candidates.length; i++){
if (target - candidates[i] < 0){
break;
}
sub.addLast(candidates[i]);
func(sub, target - candidates[i], i, candidates, res);
sub.removeLast();
}
}
}