zoukankan      html  css  js  c++  java
  • [LeetCode] Combination Sum II

     

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    Each number in C may only be used once in the combination.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
    A solution set is: 

    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]

    该题同Combination Sum类似,只不过要求结果数组中不重复

    1、先对给定candidates数组排序,这样使找出的每个组合中元素排序一致。便于去重

    2、使用std::find()函数对每个新组合判断,将不重复的组合放入结果数组中

    3、因为题中要求每个数字只能使用一次,则helper函数中迭代时,idx递增1.

    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            vector<vector<int>> res;
            vector<int> tmp;
            sort(candidates.begin(), candidates.end());
            int idx = 0;
            helper(res, tmp, candidates, target, idx);
            return res;
        }
        
        void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int target, int idx) {
            if (target < 0) {
                return;
            }
            else if (target == 0) {
                if (find(res.begin(), res.end(), tmp) == res.end())
                    res.push_back(tmp);
            }
            else {
                for (int i = idx; i < candidates.size(); i++) {
                    tmp.push_back(candidates[i]);
                    helper(res, tmp, candidates, target - candidates[i], i + 1);
                    tmp.pop_back();
                }
            }
        }
    };
    // 18 ms
  • 相关阅读:
    Ubuntu 更换软件源
    Ubuntu 配置 SOCKS5
    Ubuntu 配置 Sha-dow-socks
    frp(内网穿透)
    solr 远程代码执行(CVE-2019-12409)
    多线程处理爬虫
    python实现文件自动排序
    python 实现根据文件名自动分类移动至不同的文件夹
    Centos7如何开启任意端口服务
    centos7默认安装没有连接网络
  • 原文地址:https://www.cnblogs.com/immjc/p/8353443.html
Copyright © 2011-2022 走看看