【Leetcode】40. 组合总和 II

题目描述

在这里插入图片描述

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

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

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

题解

我们可以看这道题的前身【Leetcode】39. 组合总和,candidates中的元素是可以重复使用的,但是在这里不行。共同点是,组合本身不能重复。

不重复取元素对象在回溯搜索里,可以通过安排for循环的起点来实现。但是如果candidates本身存在重复数值怎么办?那么这里可以先排序,之后通过判断相邻两个元素是不是相等(是不是有重复数值),如果有,则跳到下一个遍历。

执行用时:4 ms, 在所有 Java 提交中击败了34.24%的用户

内存消耗:38.3 MB, 在所有 Java 提交中击败了93.91%的用户

通过测试用例:175 / 175

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    int[] candidates;
    int target;
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        this.candidates = candidates;
        this.target = target;
        Arrays.sort(candidates);
        backtracking(new ArrayList<Integer>(), 0, 0);
        return res;
    }
    
    public void backtracking(ArrayList<Integer> list, int sum, int start) {
        if (sum > target)
            return;
        if (sum == target) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
             if (i > start && candidates[i] == candidates[i - 1]) {
                 continue;
             }
            list.add(candidates[i]);
            backtracking(list, sum + candidates[i], i + 1);
            list.remove(list.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锥栗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值