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;
    }
};
相关推荐
River41639 分钟前
Javer 学 c++(十三):引用篇
c++·后端
感哥3 小时前
C++ std::set
c++
Fanxt_Ja4 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下4 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶4 小时前
算法 --- 字符串
算法
博笙困了4 小时前
AcWing学习——差分
c++·算法
NAGNIP4 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP4 小时前
大模型微调框架之LLaMA Factory
算法
echoarts4 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客4 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法