1、题目描述
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
2、算法分析
本题属于回溯算法题型中的组合求和问题,而且数组中的元素可以重复使用。
回溯算法其实就是暴力的递归求解算法。重点的是N叉树的递归思想。子结点到父节点的递归。
回溯算法大概有以下几种题型:
组合,排序,子集,切割,棋牌等。
本题是求数组中的组合的和等于target目标值。
注意:组合中的元素可以重复使用。下面分析这道题。
集合存储结果集,path存储单个路径。
①回溯函数参数的确定
回溯函数的返回值一般是void,函数名是backTracking(int[] candidates,int target,int sum,int startIndex)
sum代表的是每一个路径的和
startIndex,因为是组合,比如 12 21其实都是一个组合,组合是无序的。设定startIndex是为了去除重复的值。
②递归结束条件
sum > target的时候直接break;
sum == target的时候,说明找到了符合条件的路径,添加进去
③单层搜索
for循环的i要从startIndex开始,因为是去重。
然后将元素添加到path中,sum += candidate[i];
递归,然后回溯。
剪枝操作:
先对数组进行排序,如果发现sum + candidate[i] > target,也就是下一层的元素大于target,那么直接结束循环。
回溯模板:
void backtracking(参数) { if (终止条件) { 存放结果; return; } for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) { 处理节点; backtracking(路径,选择列表); // 递归 回溯,撤销处理结果 } }
3、代码实现
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backTracking(candidates,target,0,0);
return result;
}
public void backTracking(int[] candidates,int target,int sum,int startIndex){
if(sum > target){
return;
}
if(sum == target){
result.add(new ArrayList<>(path));
return;
}
for(int i = startIndex;i < candidates.length && (sum + candidates[i]) <= target;i++){
path.add(candidates[i]);
sum += candidates[i];
// 还是从第一个元素开始,因为i是可以重复使用的
backTracking(candidates,target,sum,i);
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
}