https://leetcode.com/problems/combination-sum-ii/
The topic is similar to the previous questions, write the code directly:
classSolution { Public: Vector<vector<int>> combinationSum2 (vector<int>& candidates,inttarget) {Sort (Candidates.begin (), Candidates.end ()); if(candidates.size () = =0) returnRes; Vector<int>temp; Helper (candidates,0, target,temp); returnRes; }Private: voidHelper (vector<int>& candidates,intIndexinttarget,vector<int>&temp) { if(target==0) Res.push_back (temp); if(target<0|| index>=candidates.size ()) { return; } for(intI=index;i<candidates.size (); i++) { if(I>index && candidates[i]==candidates[i-1])//You must ensure that the first position cannot be repeated when a value is passed down! But the first time it must be preserved, so it must be written i>index, not i>0!!. 1,1,2,5,6,7,10 8 "1,2,5" "1,2,5" "1,1,6" for this kind of situation Continue; Temp.push_back (Candidates[i]); Helper (Candidates,i+1, target-candidates[i],temp);//Note that this place should not be index, but should pass in i+1, otherwise, will appear descending sequenceTemp.pop_back (); } }Private: Vector<vector<int>>Res;};
Combination Sum II