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]
需要把子过程的结果存储起来
class Solution { public: void sub(vector<int>& c,int len,int target , map<pair<int,int>,vector<vector<int> > > &m1){ if(m1.find(pair<int,int>(len,target))!=m1.end()){ return; } else{ if(target==0){ m1[pair<int,int>(len,target)]=vector<vector<int> >(1); return; } if(len==1){ if(target%c[0]==0){ vector<vector<int>>& vec=m1[pair<int,int>(len,target)]; vec.resize(1); for(int j=0;j<target/c[0];j++)vec[0].push_back(c[0]); return; } else{ return; } } if(c[len-1]>target){ sub(c,len-1,target,m1); m1[pair<int,int>(len,target)]=m1[pair<int,int>(len-1,target)]; return; } else{ sub(c,len-1,target,m1); m1[pair<int,int>(len,target)]=m1[pair<int,int>(len-1,target)]; vector<vector<int>>& vec=m1[pair<int,int>(len,target)]; for(int i=1;i<=target/c[len-1];i++){ sub(c,len-1,target-i*c[len-1],m1); vector<vector<int>>& vec1=m1[pair<int,int>(len-1,target-i*c[len-1])]; for(int j=0;j<vec1.size();j++){ vec.push_back(vec1[j]); for(int k=0;k<i;k++) vec[vec.size()-1].push_back(c[len-1]); } } return; } } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function set<int> s; for(int i=0;i<candidates.size();i++)s.insert(candidates[i]); vector<int> iv(s.begin(),s.end()); map<pair<int,int>,vector<vector<int> > > m1; sub(candidates,candidates.size(),target,m1); vector<vector<int> >& ret= m1[pair<int,int>(candidates.size(),target)]; set<vector<int> > alp; for(int i=0;i<ret.size();i++){ sort(ret[i].begin(),ret[i].end()); alp.insert(ret[i]); } vector<vector<int> >beta(alp.begin(),alp.end()); return beta; } };