leetcode 40. Combination Sum II-回溯算法

针对LeetCode上的40. Combination Sum II问题,本文介绍了一种递归解决方案。通过先对输入数组进行排序,然后在递归过程中跳过重复元素的方式避免结果集中的重复组合。文章提供了一个Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:40. Combination Sum II

【思路-Java】递归实现

本题是 leetcode 39. Combination Sum-回溯算法|递归|非递归 的延伸,本题中给定的数组元素有重复。对于[1,1,2],如果还是采用原先的处理,结果集中肯定会有重复的元素出现,那么怎么处理呢?方法就是只对本层循环中重复元素出现进行调用,而对下一层递归中重复元素跳过递归调用。为了使重复元素相邻,我们首先要对数组排序。接下来就可以使用一行代码对重复情况进行排除:

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(res, new ArrayList<Integer>(), target, candidates, 0);
        return res;
    }
    private void dfs(List<List<Integer>> res, List<Integer> temp, int target, int[] candidates, int i) {
        if(target == 0)
            res.add(new ArrayList<>(temp));
        for(int j = i; j < candidates.length && target >= candidates[j]; j++) {
            if(j > i && candidates[j] == candidates[j-1]) continue;
            temp.add(candidates[j]);
            dfs(res, temp, target-candidates[j], candidates, j+1);
            temp.remove(temp.size()-1);
        }
    }
}
172 / 172  test cases passed. Runtime: 5 ms  Your runtime beats 77.41% of javasubmissions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值