39. 组合总和
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
示例 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]]
示例 3:
输入: candidates = [2], target = 1
输出: []
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate
中的每个元素都是独一无二的。1 <= target <= 500
思路
递归回溯。可以先排序,这样遇到和大于 target 的数值之后后面的数据就无需再进行判断了,可以减少递归次数。
解法
class Solution {
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) {
return result;
}
//先排序
Arrays.sort(candidates);
backtracking(candidates, 0, target, new ArrayList<>());
return result;
}
public void backtracking(int[] candidates, int start, int target, List<Integer> list) {
if (target == 0) {
result.add(new ArrayList<>(list));
return;
}
for (int i = start; i < candidates.length; i++) {
if (target - candidates[i] < 0) {
//数组已排序,后续数据一定不小于candidates[i],无需计算
break;
}
list.add(candidates[i]);
//由于可以重复添加,下次递归还是从 i 开始
backtracking(candidates, i, target - candidates[i], list);
list.remove(list.size() - 1);
}
}
}