Given a set of candidate numbers (C) (without duplicates) 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.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
[ [7], [2, 2, 3]] Solution: 回溯法
class Solution {public: void combination(vector & candidates, int target,vector & tmp,vector>& myvec,int start){ if(!target){ myvec.push_back(tmp); return; } for(int i=start;i <=target;i++){ tmp.push_back(candidates[i]); combination(candidates,target-candidates[i],tmp,myvec,i); tmp.pop_back(); } } vector > combinationSum(vector & candidates, int target) { vector > myvec; sort(candidates.begin(),candidates.end()); vector tmp; combination(candidates,target,tmp,myvec,0); return myvec; }};