1 Combination Sum
Given a set of candidate numbers (c) and a target number (T), find all unique combinations in C where the candidate number s sums to T. The same repeated number is chosen from C unlimited number of times.
A recursive approach can be used to solve this problem, when a set number is found equal to the target after the group is added to the container and then returned; when the sum of a group of numbers is greater than the target, returns immediately;
voidDfscombine ( vector<int>& Candidates,intLevelint& Sum,intTarget vector<int>& Mid, vector<vector<int> >& result) {if(Sum>target)return;Else if(Sum==target) {Result.push_back (mid);return; }Else{ for(intI=level;i<candidates.size (); i++) {sum+=candidates[i]; Mid.push_back (Candidates[i]); Dfscombine (Candidates,i,sum,target,mid,result); Mid.pop_back (); Sum-=candidates[i]; } } } vector<vector<int>>Combinationsum ( vector<int>& Candidates,intTarget) { vector<int>Mid vector<vector<int> >Result Sort (Candidates.begin (), Candidates.end ());intLevel=0, sum=0; Dfscombine (Candidates,level,sum,target,mid,result);returnResult }
2 Combination Sum II
Given A collection of candidate numbers (c) and a target number (T), find all unique combinations in C where the candidate Numbers sums to T. Each number in C is used once in the combination.
The difference between the question and the previous question is that the data in a given dataset can only be used once, and I just need the recursive parameters in the above question < Span class= "Mrow" id= "mathjax-span-1503" >l e v e l = i Switch l e v e l = i + 1 Can. At the same time, similar to the 3sum mentioned above, prevent the number of pop_back () from the container from being equal to the number of containers that are about to be added.
voidDfscombine ( vector<int>& Candidates,intLevelint& Sum,intTarget vector<int>& Mid, vector<vector<int> >& result) {if(Sum>target)return;Else if(Sum==target) Result.push_back (mid);Else{ for(intI=level;i<candidates.size (); i++) {sum+=candidates[i]; Mid.push_back (Candidates[i]); Dfscombine (candidates,i+1, Sum,target,mid,result);//Ensure that an element is used only onceMid.pop_back (); Sum-=candidates[i]; while(I<candidates.size ()-1&& candidates[i]== candidates[i+1]) i++;//Prevent duplication} } } vector<vector<int>>COMBINATIONSUM2 ( vector<int>& Candidates,intTarget) { vector<int>Mid vector<vector<int> >Result Sort (Candidates.begin (), Candidates.end ());intLevel=0, sum=0; Dfscombine (Candidates,level,sum,target,mid,result);returnResult }
Leetcode's Medium collection (C + + implementation) Five