Total Accepted: 54743 Total Submissions: 208167 Difficulty: Medium
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
A solution set is:
10,1,2,7,6,1,5
and target 8
, A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Subscribe to see which companies asked this question
Hide Tags
Show Similar Problems
``````````````````````````````````````````````````````````
o Judge: sum > target?
o Judge: sum==target?
o Process: sum+=source[i];
BT;
///////////////////////////////////////
//codes
class Solution {
public:
void
backTrac(vector<int>& cand, int i, int temSum, int target,
map<vector<int>,int>& mapT, vector<int>& vec){
if(temSum==target){mapT[vec]++;return ;}
else
if(temSum>target){return ;}
else{
for
(;i<cand.size();i++){
temSum+=cand[i];
vec.push_back(cand[i]);
if
(temSum>target) i = cand.size();//remove the unnecessary implementations
backTrac(cand, i+1, temSum, target, mapT, vec);
vec.pop_back();
temSum-=cand[i];
}
return ;
}
}
vector<vector<int>> combinationSum2(vector<int>&
candidates, int target) {
//if(candidates.size()==0)
//sort
sort(candidates.begin(), candidates.end());
map<vector<int>,int> mapT;
vector<int> vec;
int temSum=0;
backTrac(candidates, 0, temSum, target, mapT, vec);
vector<vector<int>> res;
map<vector<int>,int>::iterator it=mapT.begin();
for (int
i=0;i<mapT.size();i++, it++){
res.push_back(it->first);
}
return res;
}
};
No comments:
Post a Comment