zoukankan      html  css  js  c++  java
  • Combination Sum

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

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • The solution set must not contain duplicate combinations.

    For example, given candidate set 2,3,6,7 and target 7
    A solution set is: 
    [7] 
    [2, 2, 3] 

    class Solution {
    public:
        int _sum(vector<int> tmp) {
            int sum = 0;
            int i;
            for (i=0; i<tmp.size(); i++){
                sum+= tmp[i];
            }
            return sum;
        }
    
        void combination(vector<int>& candidates, vector<vector<int>> &res, vector<int> tmp, int target, int start) {
            //计算选择集的和
            int sum = _sum(tmp);
            if (start >= candidates.size() || sum > target || sum + candidates[start] > target) {
                return;
            }
            //计算该选择集是否可以包含当前数,包含多少个
            int num_add = (target - sum) / candidates[start];
            int num_mod = (target - sum) % candidates[start];
    
            int i = 0;
            //循环num_add次,每次增加一个当前数到选择集中,然后将当前数设置为下一个,进行计算
            while (i < num_add) {
                i++;
                sum += candidates[start];
                tmp.push_back(candidates[start]);
                //避免函数调用浪费时间
                if (start < candidates.size() -1) {
                    combination(candidates, res, tmp, target, start + 1);
                }
            }
            //如果当前选择集合的和正好等于target,加入结果集
            if (num_add && i == num_add && !num_mod) {
                res.push_back(tmp);
            }
            //将选择集合中所有的当前数去掉,然后计算不包含当前数时
            while (i--) {
                tmp.pop_back();
            }
            combination(candidates, res, tmp, target, start + 1);
        }
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            vector<int> tmp = {};
            int start = 0;
            vector<vector<int>> res;
            sort(candidates.begin(), candidates.end());
            combination(candidates, res, tmp, target, start);
            return res;
        }
    };
  • 相关阅读:
    zabbix添加对haproxy的监控
    【转】最近搞Hadoop集群迁移踩的坑杂记
    【转】Hive配置文件中配置项的含义详解(收藏版)
    【转】Spark-Sql版本升级对应的新特性汇总
    kylin查询出现日期对应不上的情况
    【转】saiku与kylin整合备忘录
    Eclipse中Ctrl+方法名发现无法进入到该方法中……
    maven会报Could not transfer artifact xxx错误
    【转】CDH5.x升级
    【转】Kylin实践之使用Hive视图
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5184712.html
Copyright © 2011-2022 走看看