标签:
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]
将上题Combination Sum II稍微修改就行了。
dfs(candidates,target,i+1,tmp,result_set);
改成
dfs(candidates,target,i,tmp,result_set);
表示第i位会重复。
1 class Solution { 2 public: 3 void dfs(vector<int> candidates,int target,int start,vector<int> tmp,set<vector<int>>& result_set) 4 { 5 int sum=0; 6 for(int i=0;i<tmp.size();i++) 7 { 8 sum+=tmp[i]; 9 } 10 if(sum==target) 11 { 12 sort(tmp.begin(),tmp.end()); 13 result_set.insert(tmp); 14 return; 15 } 16 else if(sum>target) 17 { 18 return; 19 } 20 for(int i=start;i<candidates.size();i++) 21 { 22 tmp.push_back(candidates[i]); 23 dfs(candidates,target,i,tmp,result_set); 24 tmp.pop_back(); 25 } 26 } 27 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 28 vector<int> tmp; 29 set<vector<int>> result_set; 30 vector<vector<int>> result; 31 dfs(candidates,target,0,tmp,result_set); 32 set<vector<int>>::iterator it; 33 for(it=result_set.begin();it!=result_set.end();it++) 34 { 35 result.push_back(*it); 36 } 37 return result; 38 } 39 };
标签:
原文地址:http://www.cnblogs.com/Sean-le/p/4815528.html