Combination Sum II
Q: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]
A: 考虑有重复元素的情况[1,1] 2 和[1] ,1。引入bvisited数组
vector<vector<int> > combinationSum2(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > result; vector<int> path; vector<bool> bvisited(num.size(),false); sort(num.begin(),num.end()); combinationsum_aux(num,target,0,0,bvisited,path,result); return result; } bool combinationsum_aux(vector<int>& num,int target,int curPos,int curSum,vector<bool>& bvisited,vector<int> &path,vector<vector<int> >& result) { if(curSum==target) { result.push_back(path); return true; }else if(curSum>target) return false; for(int i=curPos;i<num.size();i++) { if(i>0&&num[i]==num[i-1]&&!bvisited[i-1]) //注意这里 continue; path.push_back(num[i]); bvisited[i] = true; if(!combinationsum_aux(num,target,i+1,curSum+num[i],bvisited,path,result)) { path.pop_back(); bvisited[i] = false; break; //ATT: return ture not false。此时表示这一层访问结束。 } path.pop_back(); bvisited[i] = false; } return true; }