LeetCode-40-组合总和Ⅱ

题目链接:LeetCode-40-组合总和Ⅱ

代码实现

java 复制代码
class Solution {
    /**
     * 回溯算法:需要注意这个不能有重复的组合,但是组合中可以有相同的元素,其实也不是相同的元素,数值相同但索引不同
     * 1. 数组排序,为了将相等的元素放到一起
     * 2. 回溯:注意需要树层去重,树枝上不需要去重
     * 		注意:use数组加进去的时候要置为true,退回去要将状态恢复成false
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[candidates.length];
        Arrays.sort(candidates);// 排序,为了将相等的元素放到一起
        backTracking(candidates,target,0,0, res, path, used);
        return res;
    }

    /**
     * @param candidates 候选人集合
     * @param target 目标和
     * @param startIndex 起始下标,防止组合中不能出现重复的元素
     * @param curSum 当前路径的和
     * @param res 结果集
     * @param path 单层路径中的值
     * @param used  数组中哪些元素已经被使用:true:用了 ; false:没用
     */
    public static void backTracking(int[] candidates, int target, int startIndex, int curSum, List<List<Integer>> res, List<Integer> path,boolean[] used){
        if (curSum > target){
            return;
        }
        if (curSum == target){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            // used[i-1]==false 是树层去重,前一个相同的元素没有使用,那么后一个元素才能用,否则两个取得组合完全一样
            if (i > 0 && candidates[i]==candidates[i-1] && used[i-1]==false){// 当前元素和前一个元素相等,去重逻辑
                continue;
            }
            used[i] = true;
            path.add(candidates[i]);//这个不能放进去,必须单独添加,因为 list.add返回true表示添加成功,返回fasle表示添加失败,会影响后面的结果
            backTracking(candidates, target, i+1, curSum+candidates[i], res, path, used);
            path.remove(path.size()-1);
            used[i] = false;// 恢复到false
        }
    }
}
相关推荐
BirdenT15 小时前
20260518紫题训练
c++·算法
玛卡巴卡ldf16 小时前
【LeetCode 手撕算法】(多维动态规划)不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离
java·数据结构·算法·leetcode·动态规划·力扣
被AI抢饭碗的人16 小时前
算法:数据结构
数据结构·算法
运筹vivo@16 小时前
leetcode每日一题: 跳跃游戏 IV
leetcode·游戏·宽度优先
_深海凉_16 小时前
LeetCode热题100-验证二叉搜索树
算法·leetcode·职场和发展
shehuiyuelaiyuehao16 小时前
算法27,二维前缀和
开发语言·python·算法
蒟蒻的贤16 小时前
编译原理里的冲突到底是什么?
考研·算法
_深海凉_16 小时前
LeetCode热题100-二叉树的右视图
算法·leetcode·职场和发展
圣保罗的大教堂16 小时前
leetcode 1391. 检查网格中是否存在有效路径 中等
leetcode
计算机安禾16 小时前
【c++面向对象编程】第29篇:定位new(placement new):在指定内存上构造对象
开发语言·c++·算法