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:
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
先排序,然后对于每个元素,DFS遍历后续元素看和是否等于7。>7返回,<7继续,==7保存并返回。
由于集合set里面没有重复元素,所以不用考虑有重复的组合。
class Solution { public: void combin(vector<vector<int> > &res,vector<int> &temp,vector<int> &candidates,int target,int cur){ if(target<0)return; else if(target==0){res.push_back(temp);return;} else{ for(int i=cur;i<candidates.size();i++){ temp.push_back(candidates[i]); combin(res,temp,candidates,target-candidates[i],i); temp.pop_back(); } } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> >res; if(candidates.size()==0)return res; sort(candidates.begin(),candidates.end()); vector<int> temp; combin(res,temp,candidates,target,0); return res; } };