Combination Sum

发布时间:2019-06-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Combination Sum脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

标签: 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;
    
    @H_304_219@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全部内容,希望文章能够帮你解决Combination Sum所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。