Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
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.
Example 1:
Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]现在每个candidate只能用一次了,那不就在前一题的基础上从pos+1的位置开始找就好了? 但是还有别的细节要考虑:candidate里是有一样的数的,但它们是不同的candidates。比如[10, 1a, 2, 7, 6, 1b, 5]里,[1a, 1b, 6]这种情况的确能被考虑进来,但[1a, 7], [1b, 7]都会被考虑进来,就出现duplicates了。解决办法是加个小条件,还是基于对原数组排序的基础上,如果nums里当前数和前一数相等(1b和1a),就在这层规避掉这个分支。也就是说,1a,1b能在不同层被加入到同一个combination里,但不能在同一层被加入到不同的combination里。 实现:
class Solution { private: void dfs(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& combination, int pos){ if (target == 0){ res.push_back(combination); return; } for (int i=pos; i<candidates.size(); i++){ if (candidates[i] > target) return; if (i>pos && candidates[i] == candidates[i-1]) continue; combination.push_back(candidates[i]); dfs(candidates, target-candidates[i], res, combination, i+1); combination.pop_back(); } } public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> res; vector<int> combination; sort(candidates.begin(), candidates.end()); dfs(candidates, target, res, combination, 0); return res; } };