组合总和 II

260 阅读3分钟

这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战

leetcode 组合总和 II

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。 

 

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

解题: 在一个数组中查找和目标值target的不同组合,那得想办法遍历每一个数组元素来组合判断,首先这个数组是无重复元素的,并且数组的元素只能使用一次,就是这个组合里的数不能重复使用同一个数组的元素,并且不要求有序的返回,但是返回的组合可不能重复。

所以可以通过递归遍历数组,来枚举每一种组合,最后把符合条件的组合添加到结果数组里面,将遍历过程中的元素看成树形结构的,每次遍历就是走一条条路径分支,把符合条件的分支记录下来就可以了,因为需要去重,所以可以先将数组排序,这样重复元素就相邻了。

枚举过程:首先combine数组用来存储符合条件的组合,path数组就代表当前遍历到的路径分支组合,递归参数需要candidates的原数组,用了遍历获取元素组合的,target目标值,用来判断获取正确的组合,currentNum为当前递归遍历数组开始的地方,前面遍历走过的路径就不要再走了,主要是为了去除重复的组合。 递归中首先判断target的值,如果小于0了,那直接结束不需要继续了,再然后如果target=0,说明这个当前的路径组合是满足条件的,就将该组合添加到结果中,否则继续循环遍历数组下一个元素,【额外增加一个判断来去重,元素是否重复,重复就挑过当前】将当前元素添加到path路径分支中,然后把target-掉当前元素再递归下去,【这里递归下去的currentNum就不是当前循环的了,而是需要+1为i+1】,最后去掉path中的当前元素,回退上去走另外一条路径继续遍历,最后符合结果数组combine就可以了。

相对于之前可重复使用元素的方法做了几点修改:首先candidates数组先要排序;然后循环遍历需要跳过重复元素;最后递归下去的i要+1。

class Solution {
    List<List<Integer>> res = new ArrayList<>(); 
    List<Integer> path = new ArrayList<>(); 

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates, 0, target);
        return res;
    }

    public void dfs(int[] candidates, int currentNum, int target) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList(path));
            return;
        }
        for (int i = currentNum; i < candidates.length; i++) {
            if (target < candidates[i]) {
                break;
            }
            if (i > currentNum && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            dfs(candidates, i + 1, target - candidates[i]);   
            path.remove(path.size() - 1); 

        }
    }
}