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
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
思路:
典型回溯法,需要注意的就是存在重复情况的处理。
void combine(vector<vector<int>>& res, vector<int>& candidates, vector<int>& 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<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> res; if (candidates.size() == 0)return res; sort(candidates.begin(), candidates.end()); vector<int> cantemp; combine(res, candidates, cantemp, 0, target); return res; }
参考:
https://discuss.leetcode.com/topic/8916/c-backtracking-solution-with-detailed-explanation