40. 组合总和 II

40. 组合总和 II

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

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

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

来源:力扣(LeetCode)
在这里插入图片描述

思路

这题和39,组合总和大致上一致,就是回溯计算

  • 对原数据排序(方便后面的去重)
  • 确定递归的结束条件,当前和已经等于,加入结果集合中退出,当前和大于目标值,退出
  • 后面就是遍历我们当前层元素
  • 注意回溯

重点就是在遍历的过程中,去重,重复的元素避免再次使用,思想:不是当前层的第一个节点,而且当前层的当前节点的前一个节点和当前前节点一致的话,那就跳过,因为当前节点对应的值肯定被遍历了。

代码

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates,target,0);
        return result;
    }

    int num = 0 ;
    public void backtracking(int[] candidates , int target, int startIndex){
        if(num == target){
            result.add(new ArrayList<>(path));
            return;
        }else if(num > target) return;
        // 因为我们对数组排序了,所以如果当前元素的和已经超了,那就没有必要向下遍历了。
        // 我们跳出for循环,没有必要,非的使用break,可以直接再for循环的条件上做文章
        for(int i = startIndex ; i < candidates.length && num + candidates[i] <= target; i++){
            // 与39不同点,关键去重代码
            // 不是当前层的第一个节点,而且当前层的当前节点的前一个节点和当前前节点一致的话,
            // 那就跳过,因为当前节点对应的值肯定被遍历了。
            if(i > 0 && i > startIndex && candidates[i] == candidates[i - 1]) continue;
            path.add(candidates[i]);
            num += candidates[i];
            backtracking(candidates,target,i + 1);
            path.remove(path.size() - 1);
            num -= candidates[i];
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值