Combination Sum - LeetCode
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]
思路:我们通过backtracking来记录所有的值。这道题里用一个函数assist来协助完成。
对于这一串数,我们先将其排序,然后枚举每一个小于当前target的位置。假如现在枚举到了第i个数,则递归寻找从第i位开始所有累加和为target - candidates[i]的可能。
1 public: 2 void assist(vector<int>& candidates, vector<vector<int> >& res, vector<int>& cur, int target, int st) 3 { 4 if (target == 0) 5 { 6 res.push_back(cur); 7 return; 8 } 9 for (int i = st, n = candidates.size(); i < n && candidates[i] <= target; i++) 10 { 11 cur.push_back(candidates[i]); 12 assist(candidates, res, cur, target - candidates[i], i); 13 cur.pop_back(); 14 } 15 } 16 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 17 vector<vector<int> > res; 18 vector<int> cur; 19 sort(candidates.begin(), candidates.end(), less<int>()); 20 assist(candidates, res, cur, target, 0); 21 return res; 22 } 23 };