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 { public: /* cur_sum: 当前的累加和 icur : 当前候选数的下标 target :目标值 cur_re : 当前的潜在解 re : 最终的结果集 can : 候选数集 */ void dfs(int cur_sum, int icur, int target, vector<int>& cur_re, vector<vector<int> > &re, vector<int> can) { if(cur_sum > target || icur >= can.size()) return; if(cur_sum == target){ //cur_re.push_back(cur_sum); re.push_back(cur_re); return; } //(target - cur_sum >= can[i]类似剪枝,加上该判定与 //不加,时间差4-5倍。 for(int i = icur; i < can.size() && (target - cur_sum >= can[i]); ++i){ cur_sum += can[i]; cur_re.push_back(can[i]); dfs(cur_sum, i, target, cur_re, re, can); //go back cur_re.pop_back(); cur_sum -= can[i]; } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> > re; vector<int> cur_re; if(candidates.size() == 0) return re; sort(candidates.begin(), candidates.end()); if(candidates[0] > target) return re; dfs(0, 0, target, cur_re, re, candidates); return re; } };