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;
    }
};
相关推荐
炸膛坦客5 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
I_LPL6 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱6 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073216 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
炸膛坦客7 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_831824967 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~8 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you8 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018729 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563249 小时前
模板代码生成工具
开发语言·c++·算法