# missjing/leetcode

Switch branches/tags
Nothing to show
Fetching contributors…
Cannot retrieve contributors at this time
60 lines (55 sloc) 1.9 KB
 problem： 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] ------------------------------------------------------------------------------------------------------ solution： //如果candidate numbers中含有重复的元素，需要去重先，不过这题说明是set，应该就是指没有重复元素 //因为要求结果组合是有序的，所以集合需先排序，再用递归实现dfs //每个元素可以被取任意次，因此记录元素的个数也是必要的 void combinationSum_sub(int index, int target, vector &candidates, int *times, vector > &ret) { if(target < 0) return; if(index == candidates.size()) { if(target != 0) return; } if(target == 0) { vector r; for(int i = 0; i < index; i++) //这里是从0~index-1 for(int j = 1; j <= times[i]; j++) r.push_back(candidates[i]); ret.push_back(r); return; } for(int i = 0; i <= target / candidates[index]; i++) { times[index] = i; combinationSum_sub(index + 1, target - candidates[index] * i, candidates, times, ret); } } vector > combinationSum(vector &candidates, int target) { vector > ret; vector path; if(candidates.size() == 0) return ret; if(target <= 0) return ret; sort(candidates.begin(), candidates.end()); int *times = new int[candidates.size()]; for(int i = 0; i < candidates.size(); i++) times[i] = 0; combinationSum_sub(0, target, candidates, times, ret); return ret; }