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.
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]
]
class Solution {
public:
typedef vector<int>::iterator It;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
It begin = candidates.begin();
It end = candidates.end();
sort(begin, end);
combinate(begin, end, target);
return ret;
}
private:
void combinate(It begin, It end, int target) {
for (It it = begin; it != end; ++it) {
int val = *it;
if (val < target) {
ans.push_back(val);
combinate(it + 1, end, target -val);
ans.pop_back();
} else if (val == target) {
ans.push_back(val);
ret.push_back(ans);
ans.pop_back();
return;
} else {
return;
}
// 防止重复寻找
while(it + 1 != end && *it == *(it + 1)){
++it;
}
}
}
vector<vector<int> > ret;
vector<int> ans;
};