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]
vector<vector<int> > res;
vector<int> _nums;
void dfs(int target, int start, vector<int> &path){
if(target == 0) res.push_back(path);
for(int i = start; i < _nums.size(); ++i){
if(target < _nums[i]) return ; //这里如果没剪枝的话会超时
path.push_back(_nums[i]);
dfs(target - _nums[i], i, path);
path.pop_back();
}
}
vector<vector<int> >combinationSum(vector<int> &nums, int target){
_nums = nums;
sort(_nums.begin(), _nums.end());
vector<int> path;
dfs(target, 0, path);
return res;
}
原文:http://blog.csdn.net/zhengsenlie/article/details/38977093