刷刷刷 Day 27 | 40. 组合总和 II

40. 组合总和 II

LeetCode题目要求

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

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

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

示例

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

类似组合总和、组合总和III,大致的写法思路一致。这里要按要求[candidates 中的每个数字在每个组合中只能使用 一次]
既然不能重复,那么我们就要去重,去重的操作可以在找到所有结果后去重,但是耗时较大。
实际可以将数组先排序,然后在遍历过程中,来判断元素是否被重复使用过即可

上代码

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

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

    private void backtracking(int[] candidates, int target, int startIndex, int sum) {
        if (sum > target) {
            return;
        }

        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        
        for (int i = startIndex; i < candidates.length; i++) {
            if (sum > target) {
                break;
            }
            if (i > startIndex && candidates[i] == candidates[i-1]) {
                continue;
            }
            path.add(candidates[i]);
            sum += candidates[i];
            backtracking(candidates, target, i + 1, sum);
            sum -= candidates[i];
            path.removeLast();
        }
    }
}
重难点

去重

附:学习资料链接

posted @ 2023-01-28 20:21  blacksonny  阅读(14)  评论(0编辑  收藏  举报