这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
leetcode #### 组合总和
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
解题: 在一个数组中查找和目标值target的不同组合,那得想办法遍历每一个数组元素来组合判断,首先这个数组是无重复元素的,并且数组的元素可以重复使用,就是这个组合里的数可以重复使用数组的元素,并且不要求有序的返回,但是返回的组合可不能重复。
所以可以通过递归遍历数组,来枚举每一种组合,最后把符合条件的组合添加到结果数组里面,将遍历过程中的元素看成树形结构的,每次遍历就是走一条条路径分支,把符合条件的分支记录下来就可以了。
枚举过程:首先combine数组用来存储符合条件的组合,path数组就代表当前遍历到的路径分支组合,递归参数需要candidates的原数组,用了遍历获取元素组合的,target目标值,用来判断获取正确的组合,currentNum为当前递归遍历数组开始的地方,前面遍历走过的路径就不要再走了,主要是为了去除重复的组合。 递归中首先判断target的值,如果小于0了,那直接结束不需要继续了,再然后如果target=0,说明这个当前的路径组合是满足条件的,就将该组合添加到结果中,否则继续循环遍历数组下一个元素,将当前元素添加到path路径分支中,然后把target-掉当前元素再递归下去,最后去掉path中的当前元素,回退上去走另外一条路径继续遍历,最后符合结果数组combine就可以了。
class Solution {
List<List<Integer>> combine = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates, 0, target);
return combine;
}
public void dfs(int[] candidates, int target, int currentNum) {
if (target < 0) {
return;
}
if (target == 0) {
combine.add(new ArrayList(path));
return;
}
for (int i = currentNum; i < candidates.length; i++) {
if (candidates[i] <= target) {
path.add(candidates[i]);
dfs(candidates, i, target - candidates[i]);
path.remove(path.size() - 1);
}
}
}
}