leetcode Java二刷:40. 组合总和 II

23 篇文章 0 订阅
11 篇文章 0 订阅

题目:

思路:回溯

仍然,先排序,用目标值不断减去放入结果集合的数字,这样目标值与0比较即可判断是否找到解;

  • 加速剪枝:回溯的过程中,如果目标值减去当前数字小于0,那么后面所有数字都不可能满足条件了(已经排序),此时直接返回;
  • 跟上一题不同的是:数字不能重复使用,所以回溯搜索时要从下一个位置开始。
    去重:同层不能有重复,不同层可以重复,即:
    不能出现:
    在这里插入图片描述
    可以出现:
    在这里插入图片描述
  • 如何保证同层不重复呢?candidates[i] == candidates[i - 1],然而这样也会剪掉不同层重复的情况
  • 如何保证不同层可以重复呢?我们可以判断,当前位置的数字是不是第一个出现的,第一个出现,就有i == begin;不是第一个位置,就有i > begin

代码:

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> cur = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(res, cur, candidates, 0, target);
        return res;

    }
    public void backtrack(List<List<Integer>> res, List<Integer> cur, int[] candidates, int start, int target) {
        if (0 == target) {
            res.add(new ArrayList<>(cur));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
        	// 剪枝
            if (target - candidates[i] < 0) {
                return;
            }
            // 去重
            if (i > start && i - 1 >= 0 && candidates[i] == candidates[i - 1]) {
                continue;
            }
            cur.add(candidates[i]);
            // 不允许重复使用,从下一个位置i+1开始搜索
            backtrack(res, cur, candidates, i + 1, target - candidates[i]);
            cur.remove(cur.size() - 1);

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值