LeetCode 40 组合总和 II dfs

博客围绕LeetCode40组合总和II问题,介绍使用Java语言通过深度优先搜索(DFS)算法来解决该问题,体现了在算法题中运用DFS的思路与方法。

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

// 跟上题类似,只是需要去重方面考虑的多一些
// 开始暴力去重,发现效率很低...
// 后来参考大牛们的博客才发现,原来只要在每次递归的时候
// 就可以去重,比如:
// 1 1 2 2 3
// 1放入 ,第二个1在这轮循环中不需要再放入,注意是这轮循环
// 递归不到家....哎...继续加油!



class Solution {
    boolean[] flag = null;
    public List<List<Integer>> combinationSum2(int[] condidates, int target){
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
        flag = new boolean[condidates.length];
        Arrays.fill(flag, false);
        Arrays.sort(condidates);
        dfs(res, ans, condidates, 0, target);
        return res;
    }

    public void dfs(List<List<Integer>> res, List<Integer> ans, int[] condidates, int index, int target){

        if (target == 0){
            // boolean tag = false;
            // for (List<Integer> list : res){
            //     int i = 0;
            //     for (i = 0;i < list.size(); i ++){
            //         if (list.get(i) != ans.get(i))
            //             break;
            //     }

            //     if (i == list.size()){
            //         tag = true;
            //     }
            // }
            // if (!tag)
            res.add(ans);
            return ;
        }

        for (int i = index;i < condidates.length; i ++)
            if (!flag[i] && condidates[i] <= target){  
                if (i != index && condidates[i] == condidates[i - 1]) continue; // 这轮循环相同的不必再放入

                List<Integer> tmp = new ArrayList<>(ans);
                tmp.add(condidates[i]);
                flag[i] = true;
                dfs(res, tmp, condidates, i + 1, target - condidates[i]);
                flag[i] = false;
            }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值