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)
相关推荐
梭七y14 分钟前
【力扣hot100题】(033)合并K个升序链表
算法·leetcode·链表
郭涤生14 分钟前
Chapter 5: The Standard Library (C++20)_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
月亮被咬碎成星星18 分钟前
LeetCode[383]赎金信
算法·leetcode
叶孤程31 分钟前
Qt图形化界面为何总被“冷落“?
开发语言·c++·qt
嘉友39 分钟前
Redis zset数据结构以及时间复杂度总结(源码)
数据结构·数据库·redis·后端
无难事者若执43 分钟前
新手村:逻辑回归-理解03:逻辑回归中的最大似然函数
算法·机器学习·逻辑回归
写代码写到手抽筋1 小时前
C++多线程的性能优化
java·c++·性能优化
二进制人工智能1 小时前
【QT5 网络编程示例】UDP 通信
c++·qt
Maple_land1 小时前
# C++初阶——内存管理
c++
IT从业者张某某1 小时前
机器学习-04-分类算法-03KNN算法案例
算法·机器学习·分类