[力扣题解]40. 组合总和 II

题目:40. 组合总和 II

思路

回溯法

(回溯还是很难的,递归不好理解,看着代码很少吧。。。)

代码

cpp 复制代码
class Solution {
public:
    vector<vector<int>> result;
    vector<int> path;

    void function(vector<int>& candidates, int target, int sum, int startindex, vector<bool> used)
    {
        int i;
        int size;
        if(sum == target)
        {
            result.push_back(path);
            return;
        }
        if(sum > target)
        {
            return;
        }
        size = candidates.size();
        for(i = startindex; i < size; i++)
        {
            
            // used[i-1] == true : path中前面有人使用过;
            //              false : 有别的path使用过 
            if(i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false)
            {
                continue;
            }
            used[i] = true;
            sum += candidates[i];
            path.push_back(candidates[i]);
            function(candidates, target, sum, i+1, used);
            used[i] = false;
            sum -= candidates[i];
            path.pop_back();
        }

    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<bool> used (candidates.size(), false);
        result.clear();
        path.clear();
        sort(candidates.begin(), candidates.end());
        function(candidates, target, 0, 0, used);
        return result;
    }
};

难点在于去重,有2个方面的去重,从搜索树上看,

(1)同一层之间的去重;

(2)不同层之间的去重;

用人话来讲:

(1)之前有路径用过这个元素,但和当前路径无关;

(2)当前路径上用过这个元素;

在代码里面用了used这个变量来辅助去重,按照题目要求,可以出现[1, 1, 6],不能出现[1, 7], [1, 7](即使里面是2个不同的1),所以涉及到是去重情况(1)

无法容忍之前路径上用过同一个元素(可能上述情况(1)(2)两个版本的理解有点不一一对应,总之是这个意思)

相关推荐
超级码力6661 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
穿条秋裤到处跑1 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
Merlos_wind2 小时前
HashMap详解
算法·哈希算法·散列表
汉克老师2 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Yzzz-F5 小时前
Problem - 2205D - Codeforces
算法
智者知已应修善业5 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
Halo_tjn5 小时前
Java Set集合相关知识点
java·开发语言·算法
生成论实验室6 小时前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
AI科技星6 小时前
全域数学·72分册:场计算机卷【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算
科研前沿7 小时前
镜像孪生VS视频孪生核心技术产品核心优势
大数据·人工智能·算法·重构·空间计算