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
        }
    }
}
相关推荐
倔强的小石头_2 小时前
【C语言指南】函数指针深度解析
java·c语言·算法
Yasin Chen2 小时前
C# Dictionary源码分析
算法·unity·哈希算法
_Coin_-3 小时前
算法训练营DAY27 第八章 贪心算法 part01
算法·贪心算法
董董灿是个攻城狮8 小时前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki8 小时前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
qqxhb9 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
FirstFrost --sy11 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森11 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼11451412 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)12 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法