https://leetcode-cn.com/problems/combination-sum-ii/
思路:dfs+sort
void dfs(vector<int> &candidates, int value, vector<int> temp, vector<vector<int> > &res, int idx) {
if (value <= 0) {
if (value == 0) {
res.push_back(temp);
}
return;
}
for (int i = idx; i < candidates.size(); i++) {
//i和i-1不进行递归,说明不会出现重复(sort后重复元素在一起)
if (i > idx && candidates[i] == candidates[i -1]) {
continue;
}
temp.push_back(candidates[i]);
//i+1在于每个元素只能取一个
dfs(candidates, value - candidates[i], temp, res, i + 1);
temp.pop_back();
}
}
vector<vector<int> > combinationSum2(vector<int>& candidates, int target) {
//sort目的在于去重
sort(candidates.begin(), candidates.end());
vector<vector<int> > res;
if (candidates.size() == 0) {
return res;
}
vector<int> temp;
dfs(candidates, target, temp, res, 0);
return res;
}