40. 组合总和 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]
]

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

算法思路:

采用回溯算法,递归树如下,因为元素在同⼀个组合内是可以重复的,但是两个组合不能相同。不同的树枝所取数对应不同的组合, 所以我们要去重的是同一树层上的使用过的,而同一树枝上的都是一个组合里的元素,不用去重。因此可通过一个 used 数组来判断是否重复,如果 candidates[i] == candidates[i - 1] 并且 used[i - 1] == false ,就说明:前一个树枝根节点(同一个树层),使用了某个数(candidates[i - 1]),而这个树枝又使用了这个数(candidates[i] )【这样可能会出现两个一样的组合】,userd[i - 1] == false 说明不在同一棵树枝上,此时 for 循环里就应该 continue ,不选择该数。

1652591758134

1652593782972

代码实现:

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 需要排序
        Arrays.sort(candidates);
        boolean[] used = new boolean[candidates.length];
        dfs(0, 0, candidates, target, used);
        return res;
    }

    private List<List<Integer>> res = new LinkedList<>();
    private List<Integer> path = new LinkedList<>();

    // 同一个集合中可以重复(有相同的元素)
    // 不能有重复的组合
    public void dfs(int idx, int sum, int[] candidates, int target, boolean[] used) {
        if (sum >= target) {
            if (sum == target) {
                res.add(new LinkedList<>(path));
            }
            return;
        }
        for (int i = idx; i < candidates.length && sum + candidates[i] <= target; i++) {
            // 排序之后相同的一定会相邻
            // 如果相同 且 前一个没有使用,说明不在同一个集合,则跳过
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            used[i] = true;
            dfs(i + 1, sum + candidates[i], candidates, target, used);
            // 回溯
            used[i] = false;
            path.remove(path.size() - 1);
        }
    }
}

我也放荡不羁爱自由!