Combination Sum
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 (a1, a2, … , 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]
Code:
class Solution { public: void findSum(vector<int> &S,int sum,int level,int &t,vector<int> &buf,vector<vector<int>> &res){ for(int i=level;i<S.size();i++){ buf.push_back(S[i]); if(sum+S[i]==t) res.push_back(buf); if(sum+S[i]<=t) findSum(S,sum+S[i],i,t,buf,res); buf.pop_back(); } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<int> buf; vector<vector<int>> res; sort(candidates.begin(),candidates.end()); findSum(candidates,0,0,target,buf,res); return res; } };