Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
10,1,2,7,6,1,5
and target
8
,
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
与上一道题目Combination Sum很相似,只不过条件有所改动,这个题目使给定集合中可能存在相同元素,但是每个元素最多只能被使用一次。
分析:
1)同样这道题目可以使用DFS和BFS进行求解,上一题用了BFS,这里使用DFS。
2)判重方式,上一题我的判重方式直接就是在已有的解集合中进行比较判重,用在这个题目上直接就超时了;这里想了好久,比如出现如下情况:
num集合为:[2, 1, 1, 1, 1] 最终的target:4
所求得的结果应该是:[1,1,2]和[1,1,1,1]
也就是说要保证出现重复的组合有被选择的机会,有不能重复选择。
class Solution{ public: vector <vector<int>> combinationSum2(vector <int> &num, int target){ res.clear(); vector <int> temp(1,0); sort(num.begin(),num.end()); dfsFind(num, target, 0, temp); return res; } private: vector <vector <int>> res; void dfsFind(vector <int> &num, int target, int pos, vector <int> &temp){ // If current sum greater then target // then there is no need to keep try if(temp[0] > target){ return ; } //Find a combination if(temp[0] == target){ temp.erase(temp.begin()); res.push_back(temp); temp.insert(temp.begin(),target); return ; } //DFS for(int i=pos; i<num.size(); i++){ //Prevent the duplicate if(i>pos && num[i] == num[i-1]){ continue; } temp[0] += num[i]; temp.push_back(num[i]); dfsFind(num, target, i+1, temp); temp[0] -= num[i]; temp.pop_back(); } } };
//Prevent the duplicate if(i>pos && num[i] == num[i-1]){ continue; }
比如:上面的例子,如果当前temp = {2,1},此时pos = 2,那么第二个1(num[2])是可以被选择的,但是在当前的搜索分支下一个num[3] = 1就不允许被选择了。
也就是说,要保证解空间搜索树中,不能存在两条完全相同的搜索路径。