40. 组合总和 II

题目描述

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次

**注意:**解集不能包含重复的组合。

示例 1:

复制代码
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

复制代码
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

解答

cpp 复制代码
class Solution {
public:
    vector<vector<int>> res;
    vector<int> path; // 记录当前路径
    void backtrack(vector<int>& candidates, int beg, int target, vector<bool> &used)
    {
        if(target == 0) // 找到一个结果
        {
            res.push_back(path);
            return;
        }

        //
        for(int i = beg; i < candidates.size() && candidates[i] <= target; ++ i)
        {

            // 同一层使用过相同元素就跳过
            if(i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) continue;
            path.push_back(candidates[i]);
            used[i] = true;
            backtrack(candidates, i + 1, target - candidates[i],used);
            used[i] = false;
            path.pop_back();
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        // 一个路径中的某一位置不可以用重复的元素,这样会造成结果重复
        // 使用used数组标识是同一层用过某个节点还是同一个枝干用过某个节点
        // candidates[i] == candidates[i - 1] && used[i - 1] == false 表示的是同一层使用过,也就是路径上某一位置之间已经用过candidates[i - 1]元素
        // 先升序排序
        vector<bool> used(candidates.size(), false);
        path.clear();
        res.clear();
        sort(candidates.begin(), candidates.end());
        backtrack(candidates, 0, target, used);
        return res;
    }
};
相关推荐
青山是哪个青山4 分钟前
动态规划DP
算法·动态规划
Dfreedom.4 分钟前
Excel文件数据的读取和处理方法——C++
c++·数据分析·excel·数据预处理
looklight40 分钟前
7. 整数反转
c++·算法·leetcode·职场和发展
位东风1 小时前
【凌智视觉模块】rv1106 部署 ppocrv4 检测模型 rknn 推理
c++·人工智能·嵌入式硬件
Closet1231 小时前
Codeforces 2025/6/11 日志
c++·算法·codeforces
a.3021 小时前
蓝桥杯等竞赛场景下 C++ 的时间与空间复杂度深度解析
c++·蓝桥杯
水饺编程2 小时前
MFC 第一章概述
c语言·c++·windows·mfc
緈福的街口2 小时前
【leetcode】36. 有效的数独
linux·算法·leetcode
落羽的落羽3 小时前
【C++】来学习使用set和map吧
c++·学习