题目
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]
思路
思路很简单,dfs可以做,但是要注意重复的情况。比如【1,1】,1这组输入,不判断是否重复的话就会输出【【1】,【1】】,但这是不对的,正确输出应该只有一个【1】
代码
void dfs(vector<vector<int>>& re, vector<int>& candidates,vector<int>& vec, int target, int start){
if (target<0) return;
else if (target==0) re.push_back(vec);
else{
for (int i=start;i<candidates.size();++i){
if (candidates[i]==candidates[i-1]&&i>start) continue;
vec.push_back(candidates[i]);
dfs(re,candidates,vec,target-candidates[i],i+1);
vec.pop_back();
}
}
return;
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> re;
vector<int> vec;
dfs(re,candidates,vec,target,0);
return re;
}