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

解答

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;
    }
};

相关推荐

  1. 40. 组合总和 II

    2023-12-05 21:12:07       39 阅读
  2. leetcode 40. 组合总和 II

    2023-12-05 21:12:07       40 阅读
  3. LeetCode40. 组合总和 II

    2023-12-05 21:12:07       40 阅读
  4. leetcode_40.组合总和 II

    2023-12-05 21:12:07       14 阅读
  5. leetcode 40. 组合总和 II

    2023-12-05 21:12:07       11 阅读
  6. 【算法题】40. 组合总和 II

    2023-12-05 21:12:07       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-05 21:12:07       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-05 21:12:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-05 21:12:07       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-05 21:12:07       20 阅读

热门阅读

  1. oracle 去重

    2023-12-05 21:12:07       38 阅读
  2. 前端开发js中的class(类)继承

    2023-12-05 21:12:07       41 阅读
  3. 【C++】友元函数

    2023-12-05 21:12:07       43 阅读
  4. 爬虫-BeautifulSoup之XML篇

    2023-12-05 21:12:07       35 阅读
  5. Python----网络爬虫

    2023-12-05 21:12:07       34 阅读
  6. Android 解决Gradle 三方依赖冲突方法

    2023-12-05 21:12:07       44 阅读
  7. Flink流批一体计算(21):Flink SQL之Flink DDL

    2023-12-05 21:12:07       34 阅读