美文网首页
Combination Sum

Combination Sum

作者: CarlBlack | 来源:发表于2016-01-19 22:23 被阅读0次

    标签: C++ 算法 LeetCode 数组 DFS

    每日算法——leetcode系列


    问题 Combination Sum

    Difficulty: Medium

    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:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            
        }
    };
    

    翻译

    和的组合

    难度系数:中等

    给定一个一些数组成的候选集合C,和一个目标数T。现从C中选出一些数,求所有不同的取数方案使其累加和恰好等于T。
    C中的每个数都可以取若干次。
    注意

    • 所有的数(包括目标数)都为正整数
    • 组合中的元素(a1, a2, … , ak) 不能为降序排列。(ie, a1 ≤ a2 >≤ … ≤ ak)
    • 不能有重复的组合方案
      例如:候选集合2,3,6,7 和目标值7,
      答案为:
      [7] [2, 2, 3]

    思路

    此题有点像是钱的面值为1、5、10,然后用这些面值的钱组合成一个特定的数。
    不考虑加和加起来大于Int_Max的情况。
    由于每个数可以重复,可于抽象成树,root结节点有候选集合的总个数个子节点,其中每个子节点的子节点是子节点本身,重复下去。
    以候选集合2,3,6,7为例
    root节点往下,有节点2,3,6,7,从左取2这个节点push进vector<int>,每push一次将目标值减去取的节点值,如果剩余的值大于0,继续取,按深度优先取,2的子节点还是2,···
    还是画图比较清晰,找到好的画圈工具再加上

    代码

    class Solution {
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            sort(candidates.begin(),candidates.end());
            len = static_cast<int>(candidates.size());
            temAndidates = candidates;
            vector<int> combination;
            dfs(combination, target, 0);
            return result;
        }
        
    private:
        int len;
        vector<int> temAndidates;
        vector<vector<int> > result;
        
        void dfs(vector<int>& combination, int remainder,  int tempLen){
            if (tempLen >= len) {
                return;
            }
            if (remainder == 0){
                result.push_back(combination);
                return;
            } else {
                for (int i = tempLen; i < len; ++i) {
                    if (remainder < temAndidates[i]){
                        return;
                    }
                    combination.push_back(temAndidates[i]);
                    dfs(combination, remainder - temAndidates[i], i);
                    combination.pop_back();
                }
            }
        }
    };
    

    相关文章

      网友评论

          本文标题:Combination Sum

          本文链接:https://www.haomeiwen.com/subject/taxlkttx.html