40. 组合总和 II

该博客讨论了如何使用递归和回溯算法解决组合总和问题的第二变种,其中目标是找到所有可能的组合,使得数组中的数字相加等于给定的目标值,并且数组中的数字不能重复使用。博客解释了如何避免在回溯过程中重复计算相同的元素,通过排序数组和跳过相同的元素来优化解决方案。
摘要由CSDN通过智能技术生成

40. 组合总和 II

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

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(0, candidates, target, 0);
        return res;
    }
    public void backtracking(int sum,int[] candidates,int target,int startIndex){
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;
        }else{
            for(int i = startIndex; i < candidates.length && candidates[i] + sum <= target;i++){
                if(i > startIndex && candidates[i] == candidates[i - 1]) continue;
                path.addLast(candidates[i]);
                backtracking(sum + candidates[i], candidates, target, i + 1);
                path.pollLast();
            }
        }
    }
}

同一层的相同元素不纳入递归,因为这一层的相同元素比如1,1,2,中间的1会在第一个1的下层遍历中出现,可以选择选与不选,仍然可以囊括所有情况,如果中间的1保留,如果target=3,会出现2个相同组合。

这题有点绕。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值