给你一个无重复元素的整数数组 candidates 和一个目标整数 target,找出 candidates 中可以使数字和为目标数 target 的所有不同组合,并以列表形式返回。你可以按 任意顺序 返回这些组合。对于给定的输入,保证和为 target 的不同组合数少于 150 个。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
示例:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。仅有这两种组合。
思路 :以上面的示例为例子,进行思路分析
回溯算法,进行剪枝
创建一个递归函数,遍历数组中每一个数字,递归每一个枚举的数字可以选多少次;如果当前数字小于等于target,就将其加入到路径数组path中,相应的target减去当前数字的值,就是相当于选取一个分支就减去当前分支的值。
如果target == 0 时,则表示当前方案是合法的,加入到res中。
当然为了避免重复,则黄色虚线中的不再去搜索。
剩下的就在代码中写注释了
List<List<Integer>> res = new ArrayList<>(); //存储正确的结果
List<Integer> path = new ArrayList<>(); //记录路径
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates,0,target); //数组,当前枚举数字下标,目标数
return res; //返回结果数组
}
private void dfs(int[] candidates, int i, int target) {
if (target < 0) return; //当前方案不合法,超出目标值
if (target == 0){ //当前方案合法
res.add(new ArrayList<>(path)); //添加到结果集中
return;
}
for (int j = i; j < candidates.length; j++) { //循环数组,循环一次判断一次
if (candidates[j] <= target){ //数组中的值小于目标值
path.add(candidates[j]); //添加到路径数组中
dfs(candidates, j, target - candidates[j]); //因为可以重复使用,所以还是j
path.remove(path.size() - 1);//回溯,剪枝
}
}
}