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;
        }
    };
  • 相关阅读:
    ESRI Shapefiles (SHP)
    Python与开源GIS:在OGR中使用SQL语句进行查询
    [推荐]网店代销的卖家,你的宝贝名称修改了吗?
    怎么把经纬度转换成标准的度分秒单位
    如何提高淘宝流量
    十八种方法提升淘宝店流量
    mysql备份数据库几种方法
    Linux查看文件编码格式及文件编码转换
    MySQL 修改字段类型或长度
    mysql外键使用和级联
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5184712.html
Copyright © 2011-2022 走看看