LeetCode 40. Combination Sum II
原题链接
中等
作者:
迷弟
,
2020-10-02 22:29:06
,
所有人可见
,
阅读 328
题目描述
算法1
() $O()$
C++ 代码
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int> > res;
vector<int> combination;
dfs(candidates, target, res, combination, 0);
return res;
}
private:
void dfs(vector<int> &candidates, int target, vector<vector<int> > &res, vector<int> &combination, int begin) {
if (!target) {
res.push_back(combination);
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i)
if (i == begin || candidates[i] != candidates[i - 1]) {
combination.push_back(candidates[i]);
dfs(candidates, target - candidates[i], res, combination, i + 1);
combination.pop_back();
}
}
};