LeetCode 40. Combination Sum II

LeetCode 40. Combination Sum II (组合总和 II)

题目

链接

https://leetcode.cn/problems/combination-sum-ii/

问题描述

给定一个候选人编号的集合 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]
]

提示

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

思路

这里i>index,就代表是同一层,同一层不能采用相同的数,那么就可以跳过,别的思路和之前一题一样。

复杂度分析

时间复杂度 O(n2)
空间复杂度 O(n)

代码

Java

    List<List<Integer>> ans = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

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

    public void trace(int sum, int target, int[] candidates, int index) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            ans.add(new LinkedList<>(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            sum += candidates[i];
            trace(sum, target, candidates, i + 1);
            sum -= candidates[i];
            path.removeLast();
        }
    }
posted @ 2022-06-13 22:51  cheng102e  阅读(20)  评论(0编辑  收藏  举报