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
  • 相关阅读:
    vuex
    JS判断浏览器类型和详细区分IE各版本浏览器
    javascript json对象操作(基本增删改查)
    react 使用antd 按需加载
    vue-cli 3.0 豆瓣api接口使用element做分页
    vue-cli 3.0 使用axios配置跨域访问豆瓣接口
    es6之扩展运算符 三个点(...)
    Vue.js——十分钟入门Vuex
    js数组的处理使用
    如何发布自己模块到NPM
  • 原文地址:https://www.cnblogs.com/immjc/p/8353443.html
Copyright © 2011-2022 走看看