zoukankan      html  css  js  c++  java
  • [LeetCode] Combination Sum, Solution


    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 (a1a2, … , 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] 
    » Solve this problem

    [Thoughts]
    This is a normal recursion question. For each candidate, add and verify the target. If it hit, add it as a part of solution.



    [Code]
    1:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {  
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: vector<vector<int> > result;
    5: vector<int> solution;
    6: int sum=0;
    7: std::sort(candidates.begin(), candidates.end());
    8: GetCombinations(candidates,sum, 0, target, solution, result);
    9: return result;
    10: }
    11: void GetCombinations(
    12: vector<int>& candidates,
    13: int& sum,
    14: int level,
    15: int target,
    16: vector<int>& solution,
    17: vector<vector<int> >& result)
    18: {
    19: if(sum > target) return;
    20: if(sum == target)
    21: {
    22: result.push_back(solution);
    23: return;
    24: }
    25: for(int i =level; i< candidates.size(); i++)
    26: {
    27: sum+=candidates[i];
    28: solution.push_back(candidates[i]);
    29: GetCombinations(candidates, sum, i, target, solution, result);
    30: solution.pop_back();
    31: sum-=candidates[i];
    32: }
    33: }






  • 相关阅读:
    P2154 [SDOI2009]虔诚的墓主人 树状数组
    P2564 [SCOI2009]生日礼物 贪心
    P2053 [SCOI2007]修车 费用流
    P1963 [NOI2009]变换序列 倒叙跑匈牙利算法
    P3705 [SDOI2017]新生舞会 分数规划 费用流
    gym/102091
    P2698 [USACO12MAR]花盆Flowerpot 单调队列
    乌龟棋
    旅行家的预算
    组合数问题
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078919.html
Copyright © 2011-2022 走看看