Leetcode 39. Combination Sum

Source: Internet
Author: User

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 is chosen from C unlimited number of times.

Note:

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

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

classSolution { Public:    voidGetcombinationsum (intcurrentsum,vector<int>& candidates,intIndex,vector <vector<int>> &solution, Vector <int> &result,inttarget) {        if(Currentsum = = target) {//if and equal to the target, press the result into the solution and return to the previous layersolution.push_back (Result); return; }        Else{//if and less than the target, you can continue to join the value             for(inti = index; I < candidates.size (); i++) {currentsum+=Candidates[i]; if(currentsum> target) {//when the value is greater than the target, the queue cannot be compounded again, and the loop is directlyCurrentsum-=Candidates[i];  Break; } result.push_back (Candidates[i]);//press the current result to continue the recursive callgetcombinationsum (Currentsum,candidates,i,solution,result,target); Currentsum-= Candidates[i];//returns a description of the condition before a solution is found, so the last press-in is removed, and then the new value is added to the loopResult.pop_back (); }}} vector<vector<int>> Combinationsum (vector<int>& candidates,inttarget) {Vector<vector<int>>solution; Vector<int>result; intCurrentsum =0; Sort (Candidates.begin (), Candidates.end ());//sort the inputs first to make sure the output is orderlyGetcombinationsum (Currentsum,candidates,0, Solution,result,target); returnsolution; }};

Leetcode 39. Combination Sum

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.