LeetCode40 组合总和 II

前言

题目: 40. 组合总和 II
文档: 代码随想录------组合总和 II
编程语言: C++
解题状态: 没思路...

思路

所谓去重,其实就是使用过的元素不能重复选取。在树形结构中,"使用过"在这个树形结构上是有两个维度的,一个维度是同一树枝上使用过,一个维度是同一树层上使用过。

代码

cpp 复制代码
class Solution {
private:
    vector<vector<int>> res;
    vector<int> path;
    void backtracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool> used) {
        if (sum == target) {
            res.push_back(path);
            return;
        }
        for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
                continue;
            }
            sum += candidates[i];
            path.push_back(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, sum, i + 1, used);
            used[i] = false;
            sum -= candidates[i];
            path.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<bool> used(candidates.size(), false);
        path.clear();
        res.clear();
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0, 0, used);
        return res;
    }
};
  • 时间复杂度: O ( n ∗ 2 n ) O(n*2^n) O(n∗2n)
  • 空间复杂度: O ( n ) O(n) O(n)
相关推荐
感哥10 小时前
C++ 多态
c++
沐怡旸17 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
NAGNIP18 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队19 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
River41620 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥1 天前
C++ std::set
c++
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法