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.
- 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 10,1,2,7,6,1,5
and
target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
跟 Combination Sum 不同的是,候选数集中的元素只能用一次,且给定的候选数集中的元素会存在重复,这样我们对其排序尽管可以保证解元素不减有序,但重复的问题就避免不了,因为我们不知道是重复的数构成的解,每个元素我们都是相同对待的。如例子中给定的,我们可以有前面的1跟 7 够成解,其实后面的 1 跟 7 也构成的了解,就要求对最终的结果去重。Combination Sum 的代码稍作修改就可以了。
class 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){ 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]); //each item only be used once, so handle the next one. dfs(cur_sum, i + 1, target, cur_re, re, can); //go back cur_re.pop_back(); cur_sum -= can[i]; } } //why not use set? vector<vector<int> > combinationSum2(vector<int> &num, int target) { vector<vector<int> > re; vector<int> cur_re; if(num.size() == 0) return re; sort(num.begin(), num.end()); if(num[0] > target) return re; dfs(0, 0, target, cur_re, re, num); //erase the duplicate sort(re.begin(),re.end()); vector<vector<int> >::iterator vvit; vvit=unique(re.begin(),re.end()); re.erase(vvit,re.end()); return re; } };