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]
LeetCode Source
思路:DFS。或者是采用回溯法。特别注意要先对原数组排序。
class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> >ret; vector<int> temp; sort(candidates.begin(),candidates.end()); for(int i=0;i<candidates.size();++i){ dfs(ret,candidates,i,target,temp); } return ret; } void dfs(vector<vector<int> >&ret,vector<int> candidates,int i,int target,vector<int> temp){ if(candidates[i]==target){ temp.push_back(candidates[i]); ret.push_back(temp); return; } if(candidates[i]>target){ return; } if(candidates[i]<target){ temp.push_back(candidates[i]); for(int j=0;j<candidates.size()-i;++j) dfs(ret,candidates,i+j,target-candidates[i],temp); } } };
for(int j=0;j<candidates.size()-i;++j) dfs(ret,candidates,i+j,target-candidates[i],temp);
class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> >ret; vector<int> temp; sort(candidates.begin(),candidates.end()); for(int i=0;i<candidates.size();++i){ if(candidates[i]<=target) dfs(ret,candidates,i,target,temp); } return ret; } void dfs(vector<vector<int> >&ret,vector<int> candidates,int i,int target,vector<int> temp){ if(candidates[i]==target){ temp.push_back(candidates[i]); ret.push_back(temp); return; } if(candidates[i]<target){ temp.push_back(candidates[i]); for(int j=0;j<candidates.size()-i;++j) if(candidates[i+j]<=target-candidates[i]){ dfs(ret,candidates,i+j,target-candidates[i],temp); } } } };