Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]
思路:
典型回溯法,需要注意的就是存在重复情况的处理。
void combine(vector>& res, vector & candidates, vector & cantemp,int begin, int target) { if (target < 0) return; if ( target == 0) { res.push_back(cantemp); return; } for (int i = begin; i < candidates.size();i++) { //if (candidates[i]>target)return; if (i && candidates[i]==candidates[i-1]&& i>begin) continue;//避免重复元素 cantemp.push_back(candidates[i]); combine(res, candidates, cantemp, i + 1, target - candidates[i]); cantemp.pop_back(); } } vector > combinationSum2(vector & candidates, int target) { vector > res; if (candidates.size() == 0)return res; sort(candidates.begin(), candidates.end()); vector cantemp; combine(res, candidates, cantemp, 0, target); return res; }
参考: